This question already has an answer here:
-
What is EOF in the C programming language?
10 answers
As said in comments to the answer to this question: Why gcc does not produce type mismatch warning for int and char?
both -1 and 255 are 0xFF as 8 bit HEX number on any current CPU.
But EOF is equal to -1. This is a contradiction, because the value of EOF must not coincide with any valid 8-bit character. This example demonstrates it:
#include <stdio.h>
int main(void)
{
char c = 255;
if (c == EOF) printf("oops\n");
return 0;
}
On my machine it prints oops
.
How this contradiction can be explained?
When you compare an int
value to a char
value, the char
value is promoted to an int
value. This promotion is automatic and part of the C language specification (see e.g. this "Usual arithmetic conversions" reference, especially point 4). Sure the compiler could give a warning about it, but why should it if it's a valid language construct?
There's also the problem with the signedness of char
which is implementation defined. If char
is unsigned, then your condition would be false.
Also if you read just about any reference for functions reading characters from files (for example this one for fgetc
and getc
) you will see that they return an int
and not a char
, precisely for the reasons mentioned above.