Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gmmastros on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cout<<flush? 1

Status
Not open for further replies.

Sidro

MIS
Sep 28, 2002
197
0
0
US
hi,
In this statement,

cout<<&quot;hello world!&quot;<<flush;

What does the flush do?
thanks.
 
I/O is the slowest part of a program. It's faster to do a lot of I/O once than to do a little I/O a bunch of times.

So when you say:

Code:
cout << &quot;Hello, &quot;;
cout << &quot;my name is &quot;;
cout << name;
cout << &quot;.\n&quot;;
cout << &quot;Who might ye be?\n&quot;;

Instead of doing I/O for each call of the << operator, the strings get placed into cout's buffer. When the buffer gets full, cout dumps them all to wherever it's putting the characters (the screen, in many cases).

(Normally, cout automatically gets flushed when you use cin and when the program ends, so you usually see everything when you would expect to.)


That means that, in this program:

Code:
int main()
{
    cout << &quot;Hello, world!\n&quot;;

    int *p = 0;
    *p = 5; // dereference a null pointer
}

the string &quot;Hello, world!\n&quot; will probably (unless the buffer is really small) still be in cout's buffer when the program crashes, so it'll never get written to the screen.

Doing
Code:
cout << &quot;Hello, world!\n&quot; << flush
flushes the contents of cout's buffer onto the screen, so if something weird happens, at least the buffer got written.

This is usually more important with files than with cout, but it can be useful for printing debugging messages right before program crashes.


Note that endl automatically flushes the buffer, so these two lines are equivalent:

Code:
cout << &quot;Hello, world!\n&quot; << flush;
cout << &quot;Hello, world!&quot; << endl;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top