This is happening because the value -100 is being converted to a large positive value.
What you see is a result of the usual arithmetic conversions. When a signed integer value and an unsigned integer value of the same rank (int
and unsigned int
in this case) are used in an expression, the signed value is converted to the unsigned value.
These conversions are spelled out in section 6.3.1.8p1 of the C standard:
If both operands have the same type, then no further conversion is
needed.
Otherwise, if both operands have signed integer types or both have
unsigned integer types, the operand with the type of lesser
integer conversion rank is converted to the type of the operand
with greater rank.
Otherwise, 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.
Otherwise, if the type of the operand with signed integer type can
represent all of the values of the type of the operand with unsigned
integer type, then the operand with unsigned integer type is
converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned
integer type corresponding to the type of the operand with signed
integer type.
The highlighted paragraph is what applies in this case. As for how the actual conversion occurs, that is spelled out in section 6.3.1.3p2:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
So assuming an unsigned int
is 32 bits in size with no padding bytes, the maximum value it can hold is 4294967295. That means that the value -100 is converted to the value 4294967196. This means the comparison that is actually performed is 100 > 4294967295
which is false, so the else
portion of the statement is executed.