Why is ‘\n’ preferred over “\n” for output streams?

None of the other answers really explain why the compiler generates the code it does in your Godbolt link, so I thought I’d chip in.

If you look at the generated code, you can see that:

std::cout << '\n';

Compiles down to, in effect:

const char c="\n";
std::cout.operator<< (&c, 1);

and to make this work, the compiler has to generate a stack frame for function chr(), which is where many of the extra instructions come from.

On the other hand, when compiling this:

std::cout << "\n";

the compiler can optimise str() to simply ‘tail call’ operator<< (const char *), which means that no stack frame is needed.

So your results are somewhat skewed by the fact that you put the calls to operator<< in separate functions. It’s more revealing to make these calls inline, see: https://godbolt.org/z/OO-8dS

Now you can see that, while outputting '\n' is still a little more expensive (because there is no specific overload for ofstream::operator<< (char)), the difference is less marked than in your example.

Leave a Comment