Line 7 of the OP compares
i to -1.
i is an
unsigned int, -1 is a signed
int. They are both flavors of
int, so they have the same
rank. One of the rules for the Usual Arithmetic Conversions is "
if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type." Thus, -1 gets converted from
int to
unsigned int before the comparison takes place.
C99 mandates that C only permit three possible encoding techniques for integer values:
- 2's-complement
- 1's-complement
- Sign-magnitude
If we assume
ints have 16 bits, then
- Technique (unsigned int)3 (int)(-1) (unsigned int)(-1)
-
2's-complement 0x0003 0xFFFF 65535
-
1's-complement 0x0003 0xFFFE 65534
-
sign-magnitude 0x0003 0x8001 32769
-
In every case, casting -1 to an
unsigned int yields a value greater than 3.