4

I saw following code which prints output "Same" but i am having trouble in understanding this program. Please help me to understand the program.

int  main() 
{ 
   unsigned int x = -1; 
   int y = ~0; 
   if(x == y) 
      printf("same"); 
   else
      printf("not same"); 
   return 0; 
}

How the output "Same" comes? Please help me about what happens here.

Destructor
  • 14,123
  • 11
  • 61
  • 126
  • What is the result of `~0`? Please explain. – ouah Feb 02 '15 at 12:52
  • In addition to the bit equivalence of -1 and ~0, it may be good to note that the compiler does the "usual arithmetic conversions", converting ~0 to `unsigned int` type (explained e.g. [here](https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx)). The result of the comparison would be different it the numbers were converted to e.g. `int64_t`, but this is not what happens in c. A related question: [here](http://stackoverflow.com/q/7544123/509868) – anatolyg Feb 02 '15 at 13:11

1 Answers1

10

Unsigned int x = -1 has the bit flags (32 bits) :

 11111111111111111111111111111111

int 0 has the bit flags (32 bits) :

 00000000000000000000000000000000

~0 is the negate of 0 (bitwise) which is (32 bits) :

 11111111111111111111111111111111

As a side note :

 unsigned int x = -1;  

is equivalent to

 unsigned int x = UINT_MAX. 
MichaelCMS
  • 4,703
  • 2
  • 23
  • 29
  • 2
    I think the `#define` is `INT_MAX`... not `MAX_INT` – abelenky Feb 02 '15 at 12:58
  • @Zeta Done . I didn't consider having the exact number of bits the core of the information . The idea behind it is for OP to understand the behavior of the bits.I find the difference of exemplifying over 14 bits or 32 bits irrelevant. However, I do find abelenky's comment is useful. – MichaelCMS Feb 02 '15 at 13:06