I have recently read an article which stated that using \\n
is preferable to using std::endl
because endl
also flushes the stream.
When buffering occurs you will have no guarantees that the data is immediately received before a flush occurs. Under particular circumstances you might experience wrong output ordering and/or loss of information/debug data, e.g.
int main() {
std::cout << "This text is quite nice and might as well be buffered";
raise(SIGSEGV); // Oh dear.. segmentation violation
std::cout << std::endl;
}
Live Example
Output:
bash: line 7: 22235 Segmentation fault (core dumped) ./a.out
the above will not print any text since the buffering prevented the right output to be displayed.
Now if you simply add a flushing std::endl
at the end of the buffer this is what you get
int main() {
std::cout << "This text is quite nice and might as well be buffered" << std::endl;
raise(SIGSEGV); // Oh dear.. segmentation violation
std::cout << std::endl;
}
Live Example
Output:
This text is quite nice and might as well be buffered
bash: line 7: 22444 Segmentation fault (core dumped) ./a.out
This time the output is visible before the program termination.
Implications of this fact are manifold. Purely speculative: if the data were related to a server log, your app could have been crashed before the actual logging.