Why is unsigned int 1 lower than char y -1?
main() { unsigned x = 1; char y = -1; if (x > y) printf("x>y"); else printf("x<=y"); } I was expecting x>y , but I had to change the unsigned int to signed int to get the expected result.
If char equivalent to signed char :
charraised toint(integer sentences, ISO C99 ยง6.3.1.1 ยถ2)- Since
intandunsigned inthave the same rank,intconverted tounsigned int(Arithmetic Conversions, ISO C99 ยง6.3.1.8)
If char equivalent to unsigned char :
charcan be converted tointorunsigned int:- If
intcan represent allunsigned charvalues โโ(usually becausesizeof(int) > sizeof(char)),charconverted toint. - Otherwise (usually because
sizeof(char)==sizeof(int)),charconverted tounsigned.
- If
- Now we have one operand,
intorunsigned int, and the other,unsigned int. The first operand is converted tounsigned int.
Integer promotions: an expression of type of a lower rank, which int converted to int if int can contain all the values โโof the original type, otherwise to unsigned int .
Arithmetic conversions. Try converting to a larger type. When there is a conflict between the signed and unsigned, if the larger (including the case when two types have the same rank) unsigned type, you should use unsigned. Otherwise, use a signature only if it can represent all values โโof both types.
Converts to integer types (ISO C99 ยง6.3.1.3):
The conversion of a value out of range to an unsigned integer type is performed using cyclic conversion (modular arithmetic).
Converting a value out of range to a signed integer type is determined by the implementation and may cause a signal (for example, SIGFPE).
When using signed and unsigned in a single operation, the signed code received an automatic unsigned type conversion. If bit-bit -1 is considered an unsigned number, this is a very very high value. Therefore, x > y is false.