>in the above link they are saying, user should definitely NOT write code of the form
They're wrong. That code (ignoring gets) is best practice. Assuming for a moment that the author of that page isn't an idiot, I'd say there's an implicit assumption about the system/implementation here:
let the implicit output-flushing routines handle everything for you
There are two implicit flushing "routines":When a newline character is sent to the output stream in question.
When the output stream buffer is full.
It should be obvious that #2 can't be relied on if you want your user prompts to show up...well, promptly. If you want user input to be on the same line as the prompt a newline at the end of the prompt to force a flush isn't practical. The only other way to flush the stream is fflush.
The truly humorous part is how the biggest argument against fflush from that page is overhead. Let's think about this logically using the two examples:
/* Example 1 */
printf("Prompt: ");
fflush(stdout);
gets(s);
/* Example 2 */
printf("Prompt: ");
gets(s);
Assuming the "implicit flushing routines" handle everything for you, one would expect both prompts to show up before gets blocks for input. This is the normal expected behavior, and if the second example fails to do it (because there's no flush), that's a strong argument in favor of using fflush.
However, if both examples do show the prompt correctly, that means under the hood a flush is being signaled whether you call fflush or not. It's not unreasonable for an stdio implementation to tie input and output streams together for this kind of convenience.
Now for the contradiction. That page says fflush has significant overhead, but only if there's output in the buffer waiting to be flushed. If you don't call fflush and the implementation does it automatically anyway, the overhead is still there. If youdo call fflush, the overhead moves to your call and the automatic call no longer has "significant overhead" because the output buffer is now empty.
So in both examples, assuming an automatic flush, the overhead is present, and when calling fflush explicitly the overhead isn't increased by more than perhaps a no-op function call. I'm sensing faulty logic here. Of course, an automatic flush isn't guaranteed, so not using fflush is non-portable.
It gets better too:
Since the flush operation takes place between the "printf" and the "gets", any input received after the prompt but before the "gets" is simply discarded.
This is completely ridiculous. fflush operates on output streams, and flushing an output stream doesn't affect even a tied input stream. I can't even fathom what the author was thinking when he wrote this. Perhaps if we were talking about flushing an input stream in a multithreaded application with a naive implementation of stdio that didn't set appropriate locks...>When and why we need to use fflush exactly?
Use fflush when you haven't printed a newline and need the output to be written immediately.