Comparison operation on unsigned and signed integers

后端 未结 7 2122
小蘑菇
小蘑菇 2020-11-22 04:17

See this code snippet

int main()
{ 
 unsigned int a = 1000;
 int b = -1;
 if (a>b) printf(\"A is BIG! %d\\n\", a-b);
 else printf(\"a is SMALL! %d\\n\", a         


        
7条回答
  •  醉梦人生
    2020-11-22 04:45

    The hardware is designed to compare signed to signed and unsigned to unsigned.

    If you want the arithmetic result, convert the unsigned value to a larger signed type first. Otherwise the compiler wil assume that the comparison is really between unsigned values.

    And -1 is represented as 1111..1111, so it a very big quantity ... The biggest ... When interpreted as unsigned.

提交回复
热议问题