What's the difference between std::endl and '\n'

1k Views Asked by At

I've read the difference between std::endl and '\n' is that std::endl flushes the buffer and '\n' doesn't. However, as far as I know stdout on linux is line-buffered anyway, so does it mean that std::cout << ... << std::endl is the same as std::cout << ... << '\n'?

3

There are 3 best solutions below

0
On BEST ANSWER
std::ostream os;

os << std::endl; // more concise

os << '\n' << std::flush; // more explicit about flushing

Those two lines have the exact same effect.

The manual flushing is often a waste of time:

  • If the output stream is line-buffered, which should be the case for std::cout if it connects to an interactive terminal and the implementation can detect that, then printing \n already flushes.

  • If the output stream is paired with an input stream you read from directly afterwards (std::cout and std::cin are paired), then reading already flushes.

  • If you nobody waits for the data to arrive at its destination, flushing is again just going to waste.

7
On

This std::cout << ... << std::endl and this std::cout << ... << '\n' are not exactly the same. In the last one, the newline \n is streamed to the output. In most cases this will be interpreted by a console as a newline. But std::endl means (as you already mentioned) exactly flush and newline in the output console.

Assume you would write this in a document. In Linux the \n is sufficient. But Windows expects \r\n. So the new lines will not occur using \n and e.g. Notepad++ in Windows.

4
On

Use std::endl - it says exactly what you want: And end-line symbol. There is little reason to stick with archaic character-codes when you have so much more expressive and easier to use methods.

Does it print a different character? No. std::endl is expanded to \n which is then expanded to the system newline symbol (the correct form is \r\n - even Unix-Terminals in their raw data are converting \n to \r\n cause \n really only means "go down 1 line" and NOT "Got to the start of the next line". Only Unix-derived OSes use \n )

Is there a performance difference? It depends: When using an shell then no - \n flushes just the same (unless you specifically change the stream-settings to not synchronise output with printf ). When doing file-IO: Yes - here \n does not flush. So if you are fine with uncompleted writes then you can use \n

But the performance-difference is mostly irrelevant. You are talking about text output here.... Specially when it is for user-interfaces this is completely negligible as no human will read hundreds of lines every second for the flushing to have any noticeable impact.