Using scanf in a while loop

Tyler Brock picture Tyler Brock · Jun 4, 2010 · Viewed 49.5k times · Source

Probably an extremely simple answer to this extremely simple question:

I'm reading "C Primer Plus" by Pratta and he keeps using the example

while (scanf("%d", &num) == 1)...

Is the == 1 really necessary? It seems like one could just write:

while (scanf("%d", &num))

It seems like the equality test is unnecessary since scanf returns the number of objects read and 1 would make the while loop true. Is the reason to make sure that the number of elements read is exactly 1 or is this totally superfluous?

Answer

JRL picture JRL · Jun 4, 2010

In C, 0 is evaluated to false and everything else to true. Thus, if scanf returned EOF, which is a negative value, the loop would evaluate to true, which is not what you'd want.