I am reading K & R C language book, following code fragment:
char c;
while ((c = getchar()) != EOF) ...
It was mentioned that for EOF (i think it is -1) is an "out of band" return value from getchar, distinct from all possible values that getchar can return.
My questions are following:
signed char can store -127 to +127 so it can check
for -1 how it is "out of band" ? char c instead of int c?Thanks!
You have a small mistake, getchar returns an int, not a char:
int c;
while ((c = getchar()) != EOF) ...
The valid values for ascii chars are from 0 to 127, the EOF is some other (int) value.
If you keep using char, you might get into troubles (as I got into)
Well, your question is answered in the C FAQ.
Two failure modes are possible if, as in the fragment above, getchar's return value is assigned to a char.
If type char is signed, and if
EOFis defined (as is usual) as -1, the character with the decimal value 255 ('\377' or '\xff' in C) will be sign-extended and will compare equal to EOF, prematurely
terminating the input.If type char is unsigned, an actual
EOFvalue will be truncated (by having its higher-order bits discarded, probably resulting in 255 or0xff) and will not be recognized asEOF, resulting in effectively infinite input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With