In the book Linux System Programming I have read some like this:
fgetcreturns the character read as anunsigned charcast to anintor
EOFon end of file or error. A common error usingfgetcis:char c; if ((c = fgetc()) != EOF) {...}The right version of this code is:
int c; if ((c = fgetc()) != EOF) { printf("%c", (char)c); ... }
So, why can’t I cast a return value to char before comparing with EOF? Why do I have to compare EOF exactly with int? As EOF defined as -1, isn’t it normally casted to char?
Are there platforms/compilers where it is not true?
You can’t cast the return value to char because the return value could be
EOF, andEOFvalue is system-dependent and is unequal to any valid character code. linkUsually it is
-1but you should not assume that.Check this great answer from the c-faq-site:
Hope it helps!
Edited: (added the @FatalError comment on this answer, this is explained on the c-faq site but this looks more clear to me)
"If you cast it to char then EOF takes the same value as some valid character and hence becomes indistinguishable from that character. That alone should be enough justification to not make the result a char" @FatalError comment.