From K&R C
A.6.5 Arithmetic Conversions
Many operators cause conversions and yield result types in a similar way. The effect is to bring
operands into a common type, which is also the type of the result. This pattern is called the
usual arithmetic conversions.
In the code below EOF is defined to be -1 which is a signed integral constant, ch should then be converted to int and while loop should be exited eventually, but doesn’t seem to happen ! Hence the Qn.
int main()
{
unsigned char ch;
FILE* fp;
fp = fopen("myfile.txt","r");
while((ch=getc(fp)) != EOF)
{
printf("%c", ch);
}
fclose(fp);
return 0;
}
getcreturns anint(as it must be able to hold all character values as well asEOF).In your code, you truncate this value to
unsigned charwhen you assign it toch. Then you extend it toint, which will never result inEOF, as -1 truncated becomes 255, which will become theint255.