confusion about int, char, and EOF in C

EOF and 0xFF are not the same. So compiler has to distinguish between them. If you see the man page for getchar(), you'd know that it returns the character read as an unsigned char cast to an int or EOF on end of file or error.

Your while((c = getchar()) != EOF) is expanded to

((unsigned int)c != (unsigned int)EOF)

This code works because you're using signed chars. If you look at an ASCII table you'll find two things: first, there are only 127 values. 127 takes seven bits to represent, and the top bit is the sign bit. Secondly, EOF is not in this table, so the OS is free to define it as it sees fit.

The assignment from char to int is allowed by the compiler because you're assigning from a small type to a larger type. int is guaranteed to be able to represent any value a char can represent.

Note also that 0xFF is equal to 255 when interpreted as an unsigned char and -1 when interpreted as a signed char:

0b11111111

However, when represented as a 32 bit integer, it looks very different:

255 : 0b00000000000000000000000011111111
-127: 0b11111111111111111111111110000001

Tags:

C

Int

Char

Eof