-3
#include<stdio.h>
void main()
  {    
    int a = -1;
    unsigned int b =15;
      if(b==a)
           printf ("b is equal to a"); 
  }

The output is empty. negative integers are stored as 2's complement of same postive number .When a integer is compared to unsigned int integer is promoted to unsigned int by considering the 2's complement as unsigned int which is 15 here but the output is empty eventhough the 2's complement of -1 is 15

2 Answers2

2

The variable a and b

int a = -1; /* its a sign ed int, it takes 4 bytes */
unsigned int b =15;/* its a unsigned int */

And its looks like below

a = -1 => 1111 1111 | 1111 1111 | 1111 1111 | 1111 1111   

b = 15 => 0000 0000 | 0000 0000 | 0000 0000 | 0000 1111
          MSB                                         LSB

Now when you compare a and b like

if(b==a) {
    /* some code */
}

Here you are doing comparison == between two different types(a is of signed type & b is of unsigned type). So implicitly compiler will convert/promote sign int to unsigned int & then it will perform comparison ==. See this http://port70.net/~nsz/c/c11/n1570.html#6.3.1.8 for arithmetic conversation rules.

Now What is the unsigned equivalent of a or -1 ? Its all one's in 4 byte i.e 4294967295. So now it looks like

if(15==4294967295) { /*its false */
        /* some code */
}

Since if condition is false, your code doesn't print anything.

Achal
  • 11,821
  • 2
  • 15
  • 37
  • `int` is only guaranteed to be at least two bytes, and the number of bits in a byte could be something other than 8. I suppose it's also worth noting that negative numbers are not guaranteed to be in two's complement form (though I couldn't name an architecture that does not use that form) – Christian Gibbons Jun 14 '18 at 17:50
  • `int a = -1; ` Here `a` is default `sign int` & it occupies `4 byte` on 32-bit system. – Achal Jun 14 '18 at 17:55
  • Right, but it is important for one to know that this is not universal. `int` will not be 32 bits on all system. The question does not specify a platform, so it is safest for an answer to specify whenever such assumptions are made such that the answer is not correct for all platforms. It may be reasonable to skip some assumptions that only the most exotic systems use (such as non 8-bit bytes and non two's complement negatives), but there are platforms all around us that are not 32-bit. OP already already made the mistake of expecting two's complement for a 4-bit number to apply universally. – Christian Gibbons Jun 14 '18 at 18:06
0

If you change variable b to be

unsigned int b = 4294967295;

(This does assume int is being stored as 32 bits)

The print statement will run. See, https://stackoverflow.com/a/2084968/7529976