It was many years now since I stopped using std::endl
to end lines when writing to std::cout
, and started using "\n"
instead.
But now I start seeing more snippets of code using '\n'
instead, and I started wonder what might be best.
Besides the obvious that one is a string, and the other a character, is there any advantage to using this:
std::cout << variable << '\n';
Over this:
std::cout << variable << "\n";
Late addition:
When I asked this question I seemed to think that newline '\n'
flushed the buffer. Now I know that it depends.
By default std::cin
is tied to the old C stdin
FILE*
stream, and std::cout
is tied to stdout
. The flushing on newline comes from this tying. By default stdout
, if connected to a terminal, is line-buffered. That means a new line will flush its buffers. So when printing a newline using std::cout
, that will lead to stdout
being flushed.
If stdout
is not connected to a terminal (for example the output has been redirected or is piped), or if the tie between std::cout
and stdout
is broken, then newlines will not flush anything.