3

Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string? (in C)

I faced this problem while doing a networking project. I was able to narrow down the issue and reproduce it like this:

If you run this code, it wont display the text on the screen. Although it displays the text if you put \n at the end of the text or use fflush() after the printf statement.

int main(){
printf("started") ;
while(1){
}
}

Can anyone please explain this behavior?

Community
  • 1
  • 1
Aaveg Mittal
  • 31
  • 1
  • 2
  • Also of interest: [Does printf always flush the buffer on encountering a newline?](http://stackoverflow.com/questions/5229096/does-printf-always-flush-the-buffer-on-encountering-a-newline). Your question is a Very Frequently Asked Question. – DarkDust Sep 12 '11 at 06:39

1 Answers1

6

The output just doesn't get flushed to the screen without the \n.

Add fflush(stdout); after the printf and you should see the output.

aioobe
  • 383,660
  • 99
  • 774
  • 796
  • 1
    The reason is that `stdout` is _line buffered_. The solution is to either print a `"\n"` or use `fflush` to flush the buffer yourself. – Chris Lutz Sep 12 '11 at 06:38
  • Yep. Good clarification. – aioobe Sep 12 '11 at 06:40
  • exactly..but I wanted to know the reason why it is not being flushed to the screen in this case? Does it has anything to do with the while loop? – Aaveg Mittal Sep 12 '11 at 06:40
  • 1
    @Aaveg Mittal, it's not being flush, because the underlying stream (stdout) is buffered on a line-basis. This means that it simply *won't get flush until the line is completed*. It doesn't really have to do with the while loop any more than the fact that the while loop prevents any new-line characters (or closing of the stream) to take place. – aioobe Sep 12 '11 at 06:48
  • So is the compiler the one that notices the infinite loop and makes the stdout flush then? Which compiler are you using? I've tried that with Gcc compiling with -O3 and output never flushes. – Genís Sep 12 '11 at 07:44
  • *and makes the stdout flush* -- It doesn't flush in his case either. – aioobe Sep 12 '11 at 07:46