The golden rule for writing this line
while ((ch = fgetc(stdin)) != EOF)
ch must be int . Your cute trick to making ch unsigned failed is because EOF is the signed amount of int.
Ok, now we go into the depths ...
Step 1:
ch=fgetc(fp)
fgetc() returns -1 (signed int ). By golden rules, C ch receives the last octet of a bit, which is all 1 . And therefore, the value is 255 . Ch byte pattern after execution
ch = fgetc(fp);
will be that way
11111111
Step 2:
ch != EOF
Now EOF is a signed integer , and ch is an unsigned char ...
Again I refer to the golden rule C ... the smaller guy ch converted to a large int size before comparison, so his byte pattern is now
00000000000000000000000011111111 = (255)10
and EOF -
11111111111111111111111111111111 = (-1)10
There is no way that they can be equal ....... Therefore, an instruction to control the next while-loop
while ((ch = fgetc(stdin)) != EOF)
will never evaluate to false ...
And therefore, an endless cycle.
source share