"\n" or '\n' or std::endl to std::cout?

Some programmer dude picture Some programmer dude · Nov 29, 2011 · Viewed 64.8k times · Source

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.

Answer

sbi picture sbi · Nov 29, 2011

Actually, '\n' should be the default. Unless you want to also explicitly flush the stream (and when and why would you want to do that?), there is no need to use std::endl at all.1
Of course, many books and tutorials use std::endl as the default. That is unfortunate and might lead to serious performance bugs.

I suppose there's little difference between using '\n' or using "\n", but the latter is an array of (two) characters, which has to be printed character by character, for which a loop has to be set up, which is more complex than outputting a single character. Of course, when doing IO this rarely matters, but if in doubt, when you want to output one character literal, output a character literal, rather than a whole string literal.
A nice side-effect of doing so is that you communicate in your code that you intended to output only a single character, and not just accidentally did this.


1 Note that std::cout is tied to std::cin by default, which leads to std::cout being flushed before any input operation, so that any prompt will be printed before the user has to input something.