Yves
Yves

Reputation: 12431

When does the buffer flush

For cpp, I know that we have three cases to flush the buffer:

  1. When we get std::cin
  2. When we std::cout<<std::endl (or ohters things like endl)
  3. When we call some function like fflush

If I am right, there is a question:
If I just write std::cout<<"hello world"; in main and run it, I could see "hello world" at the console. So, by whom and when does the buffer flush? By the compiler? Or the buffer will flush when the main finishes?

Upvotes: 2

Views: 990

Answers (2)

ancyrweb
ancyrweb

Reputation: 1323

Stumbling on the same question, I made a little test

int main() {
    printf("t");
    // fflush(stdout);
    while(1);
    return 0;
}

It appears that without the fflush, nothing is printed out. With the flush, my little "t" appears on the console.

So, adding to the previous response, I believe flushing doesn't happen magically, but with the help of various "events", for example when the program exits, or when the buffer is full.

This answer helped me a lot understand it.

Upvotes: 0

banach-space
banach-space

Reputation: 1821

You probably want to read about std::unitbuf and std::nounitbuf. Here's a decent reference.

It might be helpful to play with some simple examples. For instance, the following code will not print Hello world ever, because there won't be automatic flushing of the output stream after any output operation:

EXAMPLE 1

#include<iostream>

int main()
{
    // ----- Don't want automatic flushing ------
    std::cout << std::nounitbuf;
    std::cout << "Hello world";

    while (1)
    {
        ;
    }
}

And this code example will indeed print Hello world, because I specified that I want the automatic flushing to be enabled:

EXAMPLE 2

#include<iostream>

int main()
{
    // ----- I do want automatic flushing ------
    std::cout << std::unitbuf;
    std::cout << "Hello world";

    while (1)
    {
        ;
    }
}

I know that the infiite while loop looks a bit silly, but it's the easiest and most portable way of pausing the code that I can think of right now (I'm sure there are better ways, though!). This way I don't get flushing because of (1) code termination, (2) destructors being called and (3) so on. It's all down to the properties of std::cout.

Upvotes: 1

Related Questions