tags:

views:

198

answers:

2

So a quick google search for fflush(stdin) for clearing the input buffer reveals numerous websites warning against using it. And yet that's exactly how my CS professor taught the class to do it.

How bad is using fflush(stdin)? Should I really abstain from using it, even though my professor is using it and it seems to work flawlessly?

+6  A: 

Simple: this is undefined behavior, since fflush is meant to be called on an output stream. This is an excerpt from the C standard:

int fflush(FILE *ostream);

ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

So it's not a question of "how bad" this is. fflush(stdin) is plainly wrong, and you mustn't use it, ever.

Eli Bendersky
Thank you! I wonder why the prof is using it then...
wrongusername
@wrongusername: unfortunately, university professors aren't always experts in programming languages
Eli Bendersky
In his defense, knowing what is and isn't "undefined behavior" basically means having the whole C specification memorized... `fflush(stdin)` is actually a very common mistake.
BlueRaja - Danny Pflughoeft
@BlueRaja: there's defense for a newbie mistake here, but **no defense for a teacher** propagating wrong knowledge! Any reference of `fflush` makes clear it's meant for output streams right in the first paragraph, you don't have to memorize the C standard for that!
Eli Bendersky
@Eli: No one can know everything. The processor will never know his mistake until someone tells him... I used `fflush(stdin)` for years until I discovered it's UB (by accident)
BlueRaja - Danny Pflughoeft
I guess university professors are also human :-)
Anders K.
Err, shouldn't one normally consult the documentation for a function before they use it? Especially a professor?
Alex
+1  A: 

According to the standard, fflush can only be used with output buffers, and obviously stdin isn't one. However, some compilers provide the use of fflush(stdin) as an extension. In that case you can use it, but it will affect portability, so you will no longer be able to use any standards-compliant compiler on earth and expect the same results.

tiftik