Originally Posted by
RyanC
but is there a logically difference between writing
(...)
? the both are indicating to a condition that simplify "whenever we didn't reach the end of the file, continue with the iterations of the while loop .."
Consider this:
Code:
int c;
while ((c = fgetc(fp)) != EOF)
{
/* do something with c */
}
The above is fine because when end of file is reached, fgetc will return EOF, hence terminating the loop before something is done with c. Notice that c is an int because EOF is an int.
Now, consider:
Code:
int c = 0;
while (c != EOF)
{
c = fgetc(fp);
/* do something with c */
}
The above is problematic because when end of file is reached, fgetc will return EOF, but something will be done with c, even though it is EOF, before the loop terminates, i.e., the check happens in a wrong place.
Likewise, consider:
Code:
int c;
while (!feof(fp))
{
c = fgetc(fp);
/* do something with c */
}
The above has the exact same problem as the previous example. So, the problem is not with feof per se: the problem is with how it is used to control the loop, i.e., the apparently obvious way to use it to control a loop is wrong.