Richard Heathfield said:
Beej said:
More precisely, the behaviour of fflush on input streams is undefined.
And indeed there is no reason to risk it, since portable alternatives
exist, and are trivial to code.
That's not quite true, depending on what "input buffer" is being
cleared. For example, if input is from a keyboard, it might be useful
to zero the typeahead buffer, in case the user incorrectly anticipated
what the prompt was going to be:
The program prompts "Enter user name: "
The user types "fred" followed by a newline.
The system is being a bit sluggish. The user assumes that the
next prompt is going to be "Enter password: " and types "qLutGg8A"
followed by a newline.
The program was recently modified so a password isn't required,
and the next prompt is actually "Enter broadcast message: ".
Fred's password is now sent out to everybody on the system.
If a call to fflush(stdin) were done before the "Enter broadcast
message: " prompt was issued, *and* if this call discarded the
password characters, then this problem might be avoided. I've used
similar facilities in the past, but not in C. I don't know whether
fflush(stdin) actually works this way on any of the systems that
support it.
This is different from reading and discarding all input up to the next
newline, which is often all you really need.
But the fact remains, fflush(stdin) invokes undefined behavior, and
any code that depends on the behavior of an implementation that
chooses to define it is non-portable, perhaps dangerously so.
(BTW, don't bother guessing what "qLutGg8A" is. It's randomly
generated; I've never used it as a password, and I never will.)