unsigned long 0 < -1?

后端 未结 4 2226
南笙
南笙 2021-02-15 10:59

I don\'t get this one!

#include 

int main()
{
    unsigned short t1 = 0, t2 = 0;

    if( t1 < t2-1 )
        printf(\" t1 < t2-1\\n\");

          


        
4条回答
  •  长发绾君心
    2021-02-15 11:13

    -1 is represented as all 1s. Therefore when interpreted as unsigned, its value is 2^32-1, which is clearly greater than 0. I'd guess that the first comparison is getting expanded to perform 32-bit signed arithmetic (perhaps due to the "1" being a signed int).

    Note that the following WILL get to the printf, because the comparison is now done in 16-bit unsigned space again:

    u32 temp = t2 - 1;
    if( t1 < temp )
        printf(" t1 < t2-1\n");
    

提交回复
热议问题