int main()
{
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.
Tried Running the code ,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
The other two answer accurately describe Ternary operator, but I think this is more relevant to the question
The output is >6
because (a + b)
casts b
to unsigned int as well.
EDIT:
See Acme's suggestion for fixing this problem. Essentially casting a
as an int
will fix this
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