I am trying to compare an unsigned int with a signed char like this:
int main(){
unsigned int x = 9;
signed char y = -1;
x < y ? printf("s") : printf("g");
return 0;
}
I was expecting the o/p to be "g". Instead, its "s". What kind of conversion is done here?
Section 6.3.1.8
, Usual arithmetic conversions, of C99 details implicit integer conversions.
If both operands have the same type, then no further conversion is needed.
That doesn't count since they're different types.
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.
That doesn't count since one is signed, the other unsigned.
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.
Bingo. x
has a higher rank than y
so y is promoted to unsigned int
. That means that it morphs from -1
into UINT_MAX
, substantially larger than 9.
The rest of the rules don't apply since we have found our match but I'll include them for completeness:
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 ranks relevant to this question are shown below. All ranks are detailed in C99, section 6.3.1.1
, Boolean, character, and integers so you can refer to that for further details.
The rank of
long long int
shall be greater than the rank oflong int
, which shall be greater than the rank ofint
, which shall be greater than the rank ofshort int
, which shall be greater than the rank ofsigned char
.The rank of
char
shall equal the rank ofsigned char
andunsigned char
.
My guess is y
is promoted to unsigned int
which becomes a big value (due to wrapping). Hence the condition is satisfied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With