Why use endl when I can use a newline character?
Solution 1
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.
Solution 2
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.
Comments
-
Moshe over 3 years
Is there a reason to use
endl
withcout
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 asendl
, or am I missing something? -
André Puel over 12 yearsAlso, isn't endl converted to the proper plataform EndLine symbol("\r\n" on windows, "\n" on Linux)?
-
Chad La Guardia over 12 yearsThe C standard specifies that
'\n'
is transparently converted to the appropriate character. So, yes, sinceendl
attaches a'\n'
, this is happening. But its not specific toendl
. -
Nawaz over 12 yearsOr, more precisely, you could write
(cout << x << '\n').flush();
. That is, all in just one statement now ascout << x << endl;
is one statement. -
Armen Tsirunyan over 12 years@Nawaz: Eschew obfuscation and surplusage. Espouse elucidation
-
Keith Thompson over 12 years@Chad: Yes -- and so does the C++ standard, which is what we're discussing here.
-
ildjarn over 12 yearsYou mean 'or any other buffered output stream`.
-
Chad La Guardia over 12 years@Keith Thompson The fact that the
'\n'
is transparently converted is not explicitly stated in the "C++" standard; it is something that carried over from the C standard. -
Keith Thompson over 12 years@Chad: Hmm, I didn't know that. But in that case, it's important to note that C++ inherits that rule from C. (I'm trying to figure out where the C++ standard says that, but I find the C++ standard harder to read than the C standard.)
-
Armen Tsirunyan over 12 years@Keith: There was a question around SO: "What can you do with C that you cannot do with C++". One of my favorite answers read: "I can lift the printed version of the annotated C standard 1000 times with one hand"
-
DirichletIsaPartyPooper over 2 yearsWhy would someFunction() execute before the first line? what could cause such a thing?