Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use endl when I can use a newline character? [duplicate]

Is there a reason to use endl with cout when I can just use \n? My C++ book says to use endl, but I don't see why. Is \n not supported as widely as endl, or am I missing something?

like image 693
Moshe Avatar asked Sep 06 '11 19:09

Moshe


People also ask

Is it better to use Endl or \n?

Both endl and \n serve the same purpose in C++ – they insert a new line. However, the key difference between them is that endl causes a flushing of the output buffer every time it is called, whereas \n does not.

When should you not use Endl?

In this section we will see why we should avoid the std::endl while printing lines into console or a file. We use std::endl for creating a newline after the current line. For few lines of IO operations, it is not making any problems. But for large amount of IO tasks, it decreases the performance.

Which is faster \n or Endl?

The difference is obvious. The second one is much faster. std::endl always flush es the stream. In turn, \n simply puts a new line character to the stream, and in most cases this is exactly what we need.

Does Endl make a new line?

The endl function, part of C++'s standard function library inserts a newline character into your output sequence, pushing the subsequent text to the next output line.


1 Answers

endl appends '\n' to the stream and calls flush() on the stream. So

cout << x << endl; 

is equivalent to

cout << x << '\n'; cout.flush(); 

A stream may use an internal buffer which gets actually streamed when the stream is flushed. In case of cout you may not notice the difference since it's somehow synchronized (tied) with cin, but for an arbitrary stream, such as file stream, you'll notice a difference in a multithreaded program, for example.

Here's an interesting discussion on why flushing may be necessary.

like image 53
Armen Tsirunyan Avatar answered Oct 17 '22 05:10

Armen Tsirunyan