When an unsigned int
value is compared to int
value, the int
value is implicitly converted to unsigned int
type. The result of that conversion is congruent to the original value modulo 2N, where N
is the number of value-forming bits in unsigned int
. This modulo equals to UINT_MAX + 1
.
For this reason initialization
unsigned int x = -1;
initializes x
with some unsigned value congruent to -1
modulo UINT_MAX + 1
. Incidentally, this is nothing else than UINT_MAX
. This value has 1
in each value-forming bit of unsigned int
object. It works that way with any unsigned type.
Expression ~0
is evaluated in the domain of signed int
type, and then y
is implicitly converted to unsigned int
in x == y
comparison. Apparently, on your platform the conversion produces the same unsigned int
value with all value-forming bits set to 1
. Hence the equality.
Initialization
unsigned int x = -4;
initializes x
with some unsigned value congruent to -4
modulo UINT_MAX + 1
. In comparison x == -4
the right-hand side is converted to unsigned type by the very same rules. Hence the equality.