2

Here is the question as shown below and the answers comes as True.I know there is some promotion which would happen when you compare an signed and unsigned.Can you please tell me how does the signed value gets promoted?

      main()
      {
          signed int a  = -5;
          unsigned int b = 2147483648;

          if(a > b)
             printf("True\n");
         else
          printf("False\n");  

      }

Advanced Thanks Maddy

Maddy
  • 503
  • 4
  • 12
  • 21

2 Answers2

3

Try printing out the converted value and see what goes on:

int main(int argc, char **argv)
  {
  signed int a  = -5;
  unsigned int ua = a;
  unsigned int b = 2147483648;

  printf("a=%d  ua=%u  b=%u\n", a, ua, b);

  if(a > b)
    printf("True\n");
  else
    printf("False\n");  
  }

prints

a=-5  ua=4294967291  b=2147483648
True

Share and enjoy.

2

As you know, the MSB of a signed number is taken as sign bit where in case of an unsigned number, it adds to the value of that number. For a negative number, say -5, the binary value is 11111111111111111111111111111011 where the MSB is the sign bit and rest of the bits give the 2's compliment of 5 (for -5). When this is converted to an unsigned number, all bits are considered to find the value of the number, including the MSB also and so, its value becomes 4294967291.

raj raj
  • 1,932
  • 1
  • 14
  • 15