9

I know endl or calling flush() will flush it. I also know that when you call cin after cout, it flushes too. And also when the program exit. Are there other situations that cout flushes?

I just wrote a simple loop, and I didn't flush it, but I can see it being printed to the screen. Why? Thanks!

for (int i =0; i<399999; i++) {

        cout<<i<<"\n";

}

Also the time for it to finish is same as withendl both about 7 seconds.

for (int i =0; i<399999; i++) {

        cout<<i<<endl;

}
J Jiang
  • 1,452
  • 10
  • 14
Arch1tect
  • 4,128
  • 10
  • 48
  • 69
  • It is an implementation detail, one that invariably depends on whether output is redirected. If it is not then flushing is automatic for the obvious reason, you expect to immediately see whatever you cout. Most CRTs have an isatty() helper function that is used to determine whether automatic flushing is required. – Hans Passant Mar 12 '14 at 08:50

1 Answers1

7

There is no strict rule by the standard - only that endl WILL flush, but the implementation may flush at any time it "likes".

And of course, the sum of all digits in under 400K is 6 * 400K = 2.4MB, and that's very unlikely to fit in the buffer, and the loop is fast enough to run that you won't notice if it takes a while between each output. Try something like this:

 for(int i = 0; i < 100; i++)
 {
   cout<<i<<"\n";
   Sleep(1000);
 }

(If you are using a Unix based OS, use sleep(1) instead - or add a loop that takes some time, etc)

Edit: It should be noted that this is not guaranteed to show any difference. I know that on my Linux machine, if you don't have a flush in this particular type of scenario, it doesn't output anything - however, some systems may do "flush on \n" or something similar.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • How about the time I measured? Shouldn't the one without `endl` be faster even though sometimes it flushes, it should flush less often right? I tried your code, it's great. Thanks! – Arch1tect Mar 12 '14 at 08:29
  • It is highly likely overtaken by the time it actually takes to output to the screen. If you send the output to NUL: or some such, you may well see a small difference (but 400k numbers is probably not enough for that - try a few million). – Mats Petersson Mar 12 '14 at 08:31
  • "overtaken" = "dominated by". – Mats Petersson Mar 12 '14 at 08:44