Why do these two numbers compare as equal and how is the comparison between x and y performed?
#include <stdio.h>
int main()
{
unsigned int x = -1;
int y = ~0; //type promotion from int to unsigned int
if (x == y)
printf("same");
else
printf("not same");
return 0;
}
The ~ operator in C++ (and other C-like languages like C and Java) performs a bitwise NOT operation - all the 1 bits in the operand are set to 0 and all the 0 bits in the operand are set to 1. In other words, it creates the complement of the original number. For more details see here.
The bitwise NOT operator has an interesting property that when applied on numbers represented by two's complement, it changes the number's sign and then subtracts one (as you can see in the above example).
If you check what the ~-operator does to y like this:
#include <stdio.h>
int main()
{
unsigned int x = -1;
printf("%i\n",x); // treat data as if singed integer
printf("%u\n",x); // treat data is if unsigned integer
int y = ~0; //type promotion from int to unsigned int
printf("%i\n",y);
if (x == y)
printf("same");
else
printf("not same");
return 0;
}
You can see:
Success time: 0 memory: 16064 signal:0
-1 same
Try out here.
Why is this so?
The bit representation for -1 in integer is (see two's complement for details)
11111111 11111111 11111111 11111111
If you read this in unsigned integer
11111111 11111111 11111111 11111111
is the largest possible unsigned int. -1 in unsigned int becomes the maximal unsigned int number due to wrap around. Therfore unsigned -1 and int ~0 are the same.