#include <stdio.h>
int main(void)
{
unsigned int a = 6;
int b = -20;
a + b > 6 ? puts("> 6") : puts("<= 6");
}
It is clear to me how the ternary operator work in this code.
I am not able to understand the addition of the signed
and unsigned
integer here.
When running this code, the output is > 6
; why?
I think the OP is not confused about the ternary operator its a different problem.
From the C99 standard, section 6.3.1.8 ("Usual arithmetic conversions"):
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.
unsigned int
and int
has the same rank, so it's equivalent to:
(a + (unsigned int)b > 6)
To fix it, you need to explicitly cast in the other direction, i.e.:
((int)a + b > 6)
So this is the reason the output will be >6
and NOT <=6