c - Why this program is output Yes, while it should either have thrown error or NO -
this question has answer here:
here + b -14 should have been lesser 'a' , hence should have printed no printed yes.
unsigned int = 6; int b = -20; if((a+b) > a){ printf("yes"); } else { printf("no"); } return 1;
according c standard (6.3.1.8 usual arithmetic conversions)
1 many operators expect operands of arithmetic type cause conversions , yield result types in similar way. purpose determine common real type operands , result. specified operands, each operand converted, without change of type domain, type corresponding real type common real type. unless explicitly stated otherwise, common real type corresponding real type of result, type domain type domain of operands if same, , complex otherwise. pattern called the usual arithmetic conversions:
...
otherwise, if operand has unsigned integer type has rank greater or equal rank of type of other operand, operand signed integer type converted type of operand unsigned integer type.
types unsigned int
, int
have same rank.
thus value of variable b
example interpreted unsigned value.
if use correct conversion specifier %u
expression ( + b )
in function call of printf
might get
#include <stdio.h> int main(void) { unsigned int = 6; int b = -20; printf( "a + b = %u\n", + b ); return 0; } + b = 4294967282
Comments
Post a Comment