cflushstdiofflush

why use fflush after printf when printf can print by itself?


I'm new to C, sorry if my question is too basic.I often see code like:

printf("%d", counter);
fflush(stdout);

my guess is that it won't print output if the buffer is not full therefore you need to flush the stdout. But I tried to not use fflush, only printf, I still have out put printed on the screen, then what's the point to use flush?


Solution

  • The main reason to use fflush after printf is timing.

    printf will display the information, at some point in time. Basically all prints to printf are buffered. fflush guarantees the buffer is emptied, meaning the print happened at the line of code that called fflush.

    In programs that tend to crash, fflush can be a very useful tool. Often the message that a user of your program wishes to receive is the last message printed just before the crash. If the program doesn't have a fflush that user will probably not get the last print statement, with the statement being lost in the buffer before display.

    This can often lead to developers looking in the wrong place in a program's source code for errors upon analyzing log files after a crash. The mental process is "well, it couldn't have made it here, because there's a printf we would have seen" when the reality is the program passed the "would have been seen" printf statement but died with that message in the buffer. If one flushes statements just after printing them, this doesn't happen (although the program runs slower, because flushing takes time).