Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string?
I was trying to answer some question on the forums, I encountered pretty interesting thing.
Here is the code :
int main()
{
int print_val = -1;
while(1)
{
printf("%d \n", ++print_val);
sleep(1);
}
}
This works perfect. Now the fun enters.. Just change line no 7 to
printf("%d ", ++print_val);(just remove linefeed!)
and now there is no output..!
So can any one please help me understand the behavior of sleep() function..? I think there is need to look at sleep() and not printf() because I have tried replacing it with fprintf() and putc(), giving just the same output.
I have tried this code on 32 bit Ubuntu as well as 32 bit Ubuntu in Virtual Machine.
Thanks
Adorn
I feel the problem is with flushing the output buffer. If you don’t put ‘\n’ at the end of your string, then output buffer won’t be flushed and printf won’t print anything. It will only start printing when the output buffer is full. Please look at this question and this one.