Many C++ books contain example code like this...
std::cout << "Test line" << std::endl;
...so I've always done that too. But I've seen a lot of code from working developers like this instead:
std::cout << "Test line\n";
Is there a technical reason to prefer one over the other, or is it just a matter of coding style?
If you didn't notice,
endl
is like pressing the ENTER KEY while"\n"
is like pressing ENTER KEY + SPACE BAR.If you intend to run your program on anything else than your own laptop, never ever use the
endl
statement. Especially if you are writing a lot of short lines or as I have often seen single characters to a file. The use ofendl
is know to kill networked file systems like NFS.There might be performance issues,
std::endl
forces a flush of the output stream.The difference can be illustrated by the following:
is equivalent to
So,
std::endl
If you want to force an immediate flush to the output.\n
if you are worried about performance (which is probably not the case if you are using the<<
operator).I use
\n
on most lines.Then use
std::endl
at the end of a paragraph (but that is just a habit and not usually necessary).Contrary to other claims, the
\n
character is mapped to the correct platform end of line sequence only if the stream is going to a file (std::cin
andstd::cout
being special but still files (or file-like)).I've always had a habit of just using std::endl because it is easy for me to see.
If you use Qt and endl, you could accidentally use the wrong
endl
, happened to me today and i was like ..WTF ??Of course that was my mistake, since i should have written
std::endl
,but if you use*endl
, qt andusing namespace std;
it depends on the order of the include files if the correctendl
will be used.Of course you could recompile Qt to use a namespace, so you get a compilation error for the example above.
EDIT: Forgot to mention, Qt's
endl
is declared in "qtextstream.h" which is part of QtCore*EDIT2: C++ will pick the correct
endl
if you have ausing
forstd::cout
or the namespacestd
, sincestd::endl
is in the same namespace asstd::cout
, C++'s ADL mechanism will pickstd::endl
.