Comparing unsigned char and EOF

前端 未结 6 2142
小蘑菇
小蘑菇 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:19

    There are several implicit conversions going on. They aren't really relevant to the specific warning, but I included them in this answer to show what the compiler really does with that expression.

    • ch in your example is of type unsigned char.
    • EOF is guaranteed to be of type int (C99 7.19.1).

    So the expression is equivalent to

    (unsigned char)ch != (int)EOF
    

    The integer promotion rules in C will implicitly convert the unsigned char to unsigned int:

    (unsigned int)ch != (int)EOF
    

    Then the balancing rules (aka the usual arithmetic conversions) in C will implicitly convert the int to unsigned int, because each operand must have the same type:

    (unsigned int)ch != (unsigned int)EOF
    

    On your compiler EOF is likely -1:

    (unsigned int)ch != (unsigned int)-1
    

    which, assuming 32-bit CPU, is the same as

    (unsigned int)ch != 0xFFFFFFFFu
    

    A character can never have such a high value, hence the warning.

提交回复
热议问题