2

I am trying to understand the behavior of std::flush, but I could not notice any difference in output, with and without using flush, (ie) every second one number is printed in both cases.

I am using Visual Studio 2015. Does my compiler automatically flush?

How can I notice a difference?

Here's the example I took from Quora:

int main()
{
    for (int i = 1; i < 11; ++i)
    {
        Sleep(1000);
        cout<<i<<" "<<flush; // same output when i run without flush
    }

    return 0;
}
RaHuL
  • 101
  • 1
  • 12
  • 1
    You can sometimes notice a missing output if you encounter a segfault right after writing without flush. In general the output will also be printed without an explicit call to flush. – Lukas-T Nov 11 '19 at 12:41
  • thanks @churill Is that only way? – RaHuL Nov 11 '19 at 12:45
  • Possible duplicate of [When does cout flush?](https://stackoverflow.com/questions/22345226/when-does-cout-flush) – Max Vollmer Nov 11 '19 at 12:58
  • See the accepted answer on the duplicate: *"There is no strict rule by the standard - only that endl WILL flush, but the implementation may flush at any time it "likes"."* – Max Vollmer Nov 11 '19 at 12:59
  • But how do i notice the difference? with and without using flush. – RaHuL Nov 11 '19 at 13:04
  • 2
    @RaHuL If you redirect the output to a file (`program > out.txt`) and then look in the file at the same time the program i running, you are more likely to see a difference. At least on posix systems. Not sure how it'll behave on Windows. – Ted Lyngmo Nov 11 '19 at 13:09

0 Answers0