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:
getchar()
returns int, why is char c; c = getchar();
a valid usage of the function? Does C automatically type cast to char in this case, and in the case that getchar()
is replaced with getc(fp)
or fgetc(fp)
?fgetc()
or the other two functions return EOF? Would it again try and cast to char like before but then fail? What gets stored in ch
, if anything?ch == EOF
a valid comparison, since EOF cannot be represented by a char variable?If getchar() returns int, why is char c; c = getchar(); a valid usage of the function?
It's not. Just because you can write and compiler (somehow) allows you to compile it, does not make a code valid.
I believe the above answers all the questions.
Just to add, in case EOF
is returned, it cannot be stored in a char
. Signedness of a char
is implementation defined, thus, as per chapter 6.3.1.3, C11
When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.