#include<stdio.h>
void main()
{
unsigned x = 1;
signed char y = -1;
if(x > y)
printf("x > y");
else if(x == y)
printf("x == y");
else
printf("x < y");
printf("\n");
printf("%d",(signed char)x);
printf("\n");
printf("%d",(unsigned int)y);
}
OUTPUT:
x < y
1
-1
I expected the output to be x == y as during comparison signed character is supposed to be converted to unsigned int? Please explain me how x < y...
Well, you're halfway there.
When a value of
-1
is converted (promoted, actually) tounsigned int
, the representation produces the biggest possible value representable by the type. Hence, the promoted value becomes greater thanx
which is1
.Quoting
C11
, chapter §6.3.1.8, Usual arithmetic conversionsTo 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,
To add to above, the usage
and
are no good.
%d
expects a signed integer type (int
) as argument.signed char
value, use%hhd
unsigned int
, use%u