There is the following code from part of a function that I have been given:
char ch;
ch = fgetc(fp);
if (ch == EOF)
return -1;
Where fp
is a pointer-to-FILE/stream passed as a parameter to the function.
However, having checked the usage of fgetc()
,getc()
and getchar()
, it seems that they all return type int rather than type char because EOF does not fit in the values 0-255 that are used in a char, and so is usually < 0 (e.g. -1). However, this leads me to ask three questions:
- If
getchar()
returns int, why ischar c; c = getchar();
a valid usage of the function? Does C automatically type cast to char in this case, and in the case thatgetchar()
is replaced withgetc(fp)
orfgetc(fp)
? - What would happen in the program when
fgetc()
or the other two functions return EOF? Would it again try and cast to char like before but then fail? What gets stored inch
, if anything? - If EOF is not actually a character, how is
ch == EOF
a valid comparison, since EOF cannot be represented by a char variable?