0

I know about fflush(stdin) that it is undefined behavior according to standard. But when it comes to stdout, there is no such restriction. I did google to get the concept of using stdout as a parameter of fflush, but I couldn't get it.

Can someone elaborate the fflush function having stdout as a parameter with an easy example?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Abhishek Jaiswal
  • 288
  • 2
  • 14

1 Answers1

0

When printing (e.g. printf), the output is put into a buffer and may not be written to the console until a newline character is displayed. To ensure that everything in the buffer is written to the console, fflush(stdout) may be used.

One example is displaying the progress of some process:

   for(int i = 0; i < 100; i++)
   {
       <...calculation...>
       printf("."); // Print a dot after each iteration to show progress
       fflush(stdout);   // The dot may be buffered. This ensures that it is displayed immediately
   }
nielsen
  • 5,641
  • 10
  • 27
  • Sorry but I don't really get the example,wouldnt the printf just print the dot immediately just like it does for printing other things? I don't see the point of fflush here. – blake Apr 29 '21 at 08:10
  • 1
    @blake Not necessarily. As far as I know the behavior is not standardized, but it is not uncommon for `stdout` to be line-buffered such that output is inserted in a buffer and not written to the screen until a newline is encountered. Hence whether or not the `printf(".")` results in a dot being printed immediately is system-dependent. Flushing `stdout` ensures consistent behavior at the cost of a possible performance penalty. – nielsen Apr 29 '21 at 10:31
  • ah that makes sense ,thanks for the reply. – blake Apr 29 '21 at 12:52