#include<stdio.h>
int main(){
unsigned int a = 6;
int b = -20;
( a+b > 6 ) ? puts( "a") : puts( "b");// if a+b > 6 then a else b
}
I presumed that the output should be "b" but it wasn't.
output: a
#include<stdio.h>
int main(){
unsigned int a = 6;
int b = -20;
( a+b > 6 ) ? puts( "a") : puts( "b");// if a+b > 6 then a else b
}
I presumed that the output should be "b" but it wasn't.
output: a
C99 standard, section 6.3.1.8
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.
So here b
(value= -20) is converted to unsigned type
(a large value), it will be equivalent to -
( a+(unsigned int)b > 6 )
Therefore , output is a
not b
The type of the expression a + b
is unsigned int
, which is the result of arithmetic conversions that are applied whenever the arithmetic operators are used on operands of different types. Each operand is first converted to this common type, and the result of converting -20
to an unsigned int
is a very large value.