Flush the Output Buffer

◀ Using namespace std▶ Assignment Operator Between Two Structure Instances
Amazon This is a very important aspect of C++’s output buffer. As discussed in Chapter 5, inserting print statements is useful in debugging but you need to make sure the output buffer is flushed so that you can see the output immediately.

Let’s explore how cout works. Whenever you use cout to output something, ostream buffers it but does not send it to the output device immediately. Only when the buffer is flushed will the output get sent to the destination. Here are several ways for a buffer to be flushed:
  • The buffer is full (usually 512 bytes).
  • cout is waiting for an input.
  • cout receives a newline via endl.
  • cout receives a specific command telling it to flush.
  • The current function terminates.
The reason for this behavior is to save time. For example, if the standard output is associated with a file, you don’t want a program to send one byte 512 times while it can send 512 bytes once. Try running the following program:
using namespace std;

int main(){
	int i;	
	return 0;
When the program runs, it actually waits for a while, then outputs begin…end at the same time. This is because the buffer is not flushed before control reaches the for loop. You can append endl to the first cout and the buffer will be flushed before the program waits. An alternative is to use the keyword flush as in
to tell cout explicitly to flush the buffer (or use flush(cout)).

Another way to flush the buffer is when the current function terminates. In the above program, if you take out endl at the end of the second cout, the buffer won’t be flushed.

But when program reaches the end of main, the buffer is flushed and output printed onscreen. You can write a function outside main and call it. When that function terminates, the output buffer is flushed.

Having examined the somewhat strange yet reasonable behavior of cout, you should realize that if you want to insert print statements for debugging purposes, you need to flush the buffer in order to see the outputs immediately.

Next let’s look at assignment behavior of pointers versus objects!
◀ Using namespace std▶ Assignment Operator Between Two Structure Instances

Questions? Let me know!