Comparison operation on unsigned and signed integers

后端 未结 7 1916
小蘑菇
小蘑菇 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:38

    You are doing unsigned comparison, i.e. comparing 1000 to 2^32 - 1.

    The output is signed because of %d in printf.

    N.B. sometimes the behavior when you mix signed and unsigned operands is compiler-specific. I think it's best to avoid them and do casts when in doubt.

    0 讨论(0)
  • 2020-11-22 04:41

    On a typical implementation where int is 32-bit, -1 when converted to an unsigned int is 4,294,967,295 which is indeed ≥ 1000.

    Even if you treat the subtraction in an unsigned world, 1000 - (4,294,967,295) = -4,294,966,295 = 1,001 which is what you get.

    That's why gcc will spit a warning when you compare unsigned with signed. (If you don't see a warning, pass the -Wsign-compare flag.)

    0 讨论(0)
  • 2020-11-22 04:44
     #include<stdio.h>
     int main()
     {
       int a = 1000;
       signed int b = -1, c = -2;
       printf("%d",(unsigned int)b);
       printf("%d\n",(unsigned int)c);
       printf("%d\n",(unsigned int)a);
    
       if(1000>-1){
          printf("\ntrue");
       }
       else 
         printf("\nfalse");
         return 0;
     }
    

    For this you need to understand the precedence of operators

    1. Relational Operators works left to right ... so when it comes

      if(1000>-1)

    then first of all it will change -1 to unsigned integer because int is by default treated as unsigned number and it range it greater than the signed number

    -1 will change into the unsigned number ,it changes into a very big number

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 04:48

    while comparing a>b where a is unsigned int type and b is int type, b is type casted to unsigned int so, signed int value -1 is converted into MAX value of unsigned**(range: 0 to (2^32)-1 )** Thus, a>b i.e., (1000>4294967296) becomes false. Hence else loop printf("a is SMALL! %d\n", a-b); executed.

    0 讨论(0)
  • 2020-11-22 04:58

    Find a easy way to compare, maybe useful when you can not get rid of unsigned declaration, (for example, [NSArray count]), just force the "unsigned int" to an "int".

    Please correct me if I am wrong.

    if (((int)a)>b) {
        ....
    }
    
    0 讨论(0)
提交回复
热议问题