“\n” or ‘\n’ or std::endl to std::cout? [duplicate]

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.

Leave a Comment