Comparison operation on unsigned and signed integers

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

     #include
     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

提交回复
热议问题