Comparing unsigned char and EOF

前端 未结 6 2185
小蘑菇
小蘑菇 2020-11-29 08:59

when the following code is compiled it goes into an infinite loop:

int main()
{
    unsigned char  ch;
    FILE *fp;
    fp = fopen(\"abc\",\"r\");
    if(fp         


        
6条回答
  •  广开言路
    2020-11-29 09:41

    When you compare an unsigned int with a signed int, it converts the signed int to unsigned int and compares them. Hence when you are reading the file with an unsigned int 'ch', reading an EOF gives you 2^32+1 (on a 4 byte int machine) and when comparing it with EOF, it converts EOF to unsigned which is also 2^32+1 and hence the program stops!

    If you use unsigned char ch, when you read the file, reading EOF returns 2^32+1, and this will be casted to unsigned char, which truncates the value to first 8 bits (on a 1 byte char machine) and gives you an output of 255. Hence you are comparing 255 and 2^32+1, causing an infinite loop.

    The problem here is truncating before compare.

    If you use

    while((ch = fgetc(fp))!=(unsigned char)EOF)
        printf("%c",ch);
    

    you program will run fine!

提交回复
热议问题