I expected the output to be x == y as during comparison signed character is supposed to be converted to unsigned int?
Well, you're halfway there.
When a value of -1
is converted (promoted, actually) to unsigned int
, the representation produces the biggest possible value representable by the type. Hence, the promoted value becomes greater than x
which is 1
.
Quoting C11
, chapter §6.3.1.8, Usual arithmetic conversions
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.
To clarify, the promotion does not mean, it removes the signedness. The operand (value), with the sign, is treated as the promoted type. The value is determined from the bit representation. The details: chapter §6.3.1.3,
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.
To add to above, the usage
printf("%d",(signed char)x);
and
printf("%d",(unsigned int)y);
are no good. %d
expects a signed integer type (int
) as argument.
- If you want to print a
signed char
value, use %hhd
- If you want to print an
unsigned int
, use %u