Moshe
Moshe

Reputation: 58097

Why use endl when I can use a newline character?

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?

Upvotes: 68

Views: 107949

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133092

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.

Upvotes: 88

Paul Manta
Paul Manta

Reputation: 31597

endl is more than just an alias for the \n character. When you send something to cout (or any other output stream), it does not process and output the data immediately. For example:

cout << "Hello, world!";
someFunction();

In the above example, there's is some chance that the function call will start to execute before the output is flushed. Using endl you force the flush to take place before the second instruction is executed. You can also ensure that with the ostream::flush function.

Upvotes: 8

Related Questions