Difference between '\n' and endl

There is one major difference between these two of them. It is buffering and flushing. 

When you send output to a stream, it does not necessarily get printed immediately. Rather, it may wait in a buffer until some unspecified event, e.g. buffer full enough, reading from input, or exit from program. The details may vary.

Buffering makes it faster to print a large amount of output, particularly if you are producing the output bit-by-bit (e.g. one character at a time). However, it is a nuisance for output used in debugging (e.g. a statement that informs you that step 3 of your algorithm has been finished).

Buffering & Flushing

Forcing all buffered output to actually be printed is known as "flushing" the stream. A flush can be forced by calling the flush function associated with each output stream, inserting the magic variable flush into the stream, or inserting endl.

cout << flush;
cout.flush();
cout << endl;

Reference

Buffering and flushing

Comments