Using endl and flush

Output streams must be flushed for their contents to be written to the output device. Consider the following:

cout << "This first calculation may take a very long time\n";
firstVeryLongCalc();
cout << "This second calculation may take even longer\n";
secondVeryLongCalc();
cout << "All done!";

If the functions called in this excerpt do not themselves perform input or output to the standard I/O streams, the first message will be written to the cout buffer before firstVeryLongCalc() is called. The second message will be written before secondVeryLongCalc() is called, but the buffer may not be flushed (written out to the physical output device) until an implicit or explicit flush operation occurs. As a result, the above program displays its messages about expected delays after the delays have already occurred. If you want the output to be displayed before each function call, you must flush the output stream.

A stream is flushed implicitly in the following situations:

The above example can be corrected so that output appears before each calculation begins, as follows:

cout << "This first calculation may take a very long time\n";
cout.flush();
firstVeryLongCalc();
cout << "This second calculation may take even longer\n";
cout.flush();
secondVeryLongCalc();
cout << "All done!"
cout.flush();

Placing endl or flush in an Output Stream

The endl and flush manipulators give you a simple way to flush an output stream:

cout << "This first calculation may take a very long time" << endl;
firstVeryLongCalc();
cout << "This second calculation may take even longer" << endl;
secondVeryLongCalc();
cout << "All done!" << flush;

Placing the flush manipulator in an output stream is equivalent to calling flush() for that output stream. When you place endl in an output stream, it is equivalent to placing a new-line character in the stream, and then calling flush().

Avoid using endl where the new-line character is required but buffer flushing is not, because endl has a much higher overhead than using the new-line character. For example:

cout << "Employee ID:  " << emp.id   << endl
     << "Name:         " << emp.name << endl
     << "Job Category: " << emp.jobc << endl
     << "Hire date:    " << emp.hire << endl;

is not as efficient as:

cout <<   "Employee ID:  " << emp.id
     << "\nName:         " << emp.name
     << "\nJob Category: " << emp.jobc
     << "\nHire date:    " << emp.hire << endl;

You can include the new-line character as the start of the character string that immediately follows the location where the endl manipulator would have been placed, or as a separate character enclosed in single quotation marks:

cout << "Salary:       " << emp.pay        << '\n'
     << "Next raise:   " << emp.elig_raise << endl;

Flushing a stream generally involves a high overhead. If you are concerned about performance, only flush a stream when necessary.