Reputation: 11431
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!
Upvotes: 3
Views: 1068
Reputation: 32429
Whatever value EOF has depends on your platform. Take a look at stdio.h too see its actual definition.
Upvotes: 2
Reputation: 182619
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
EOF
is 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
EOF
value 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.
Upvotes: 5
Reputation: 137282
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)
Upvotes: 6