flushing question

Hello,

I am trying to conceptually understand cout flushing.

consider the following

1
2
3
4
5
6
7
int func() {
cout << "anything";
func1(); // definitions of func1 and func2 are not known
cout << func2()
cout.flush();
return 0;
}


Why does cout not always flush in this case?

or in this case:

1
2
3
4
5
6
7
int func() {
cout << "anything";
func1(); // definitions of func1 and func2 are not known
cout << func();
cout.flush();
return 0;
}


I replaced func2 with func. will cout ever flush in this case? or will the recursion not allow this?

Thank you
Last edited on
cout will flush when:

1) You tell it to
or
2) Its internal buffer gets full
or
3) The implementation decides to (some implementations might flush automatically on a new line... or when you poll to get data from cin)

Why does cout not always flush in this case?


Because you're not telling it to, you're not giving it enough data to fill its internal buffer, and you're not doing anything else that the implementation considers to be "flushworthy".

I replaced func2 with func. will cout ever flush in this case? or will the recursion not allow this?


If you keep giving more and more data to cout, yes, it will eventually flush because its buffer will fill.

However whether or not that happens before you overflow the stack due to infinite recursion, there is no way of knowing.
std::cout will also flush
4) just before any read from std::cin
5) just before any output to std::cerr
6) before the program ends.
I didn't know #4 was guaranteed, cool.
@Disch

Doesn't the cout.flush() tell it to flush? Why doesn't this work? Should I remove it completely and implement another way to flush it? like endl?

A better question is:

"How can I ensure it will flush in the first case?"
Last edited on
#s 4-5 are guaranteed because cout and cerr are tie()ed to cin.
Doesn't the cout.flush() tell it to flush?


Yes.

Why doesn't this work?


It does. cout is flushing. Whether or not there's anything in the buffer is questionable though.

A couple of things that might be happening (listed in order of how likely I think they are):

1) It is flushing properly as you'd expect, and the text is being printed to the console, but the program exits and the window closes before you get to see it.

2) func1() and/or func2() are emptying the buffer somehow, so that when it's flushed, there is nothing to flush.

3) func1() and/or func2() are flushing the buffer, but then clearing the screen so you don't see what got flushed.

4) Your implementation is horribly, horribly broken and doesn't flush when you tell it to.
Topic archived. No new replies allowed.