Reputation: 175
why does below program gives the output that b is greater than a? Even though b contains -2.
void main()
{
unsigned int a=12;
int b=-2;
if(a>b)
printf("a is greater");
else
printf("b is greater");
getch();
}
Upvotes: 3
Views: 168
Reputation: 153468
To perform the comparison, both operands are first converted to the same type. In this case, int b
is converted to the higher ranking unsigned
. For the comparison values, it is then 12 > (-2 + (UINTMAX + 1))
? which is false.
To compare in the usual mathematical sense:
unsigned int a;
int b;
if ((b < 0) || (a > b)) printf("a is greater");
Upvotes: 0
Reputation: 134326
First, to quote the C11
standard for relational operators, chapter 6.5.8
If both of the operands have arithmetic type, the usual arithmetic conversions are performed.
Now, following the description in chapter 6.3.1.8, Usual arithmetic conversions, if you try to perform arithmetic operation between a signed
and an unsigned
integer (type), the signed
one will get promoted to unsigned
type (higher rank) and then the operation will take place.
So, here, for the comparison, the value of b
is getting converted to unsigned
type and you're getting the wrong output there.
To quote the relevant part, from the same chapter
[...] Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
You can also check on the usual arithmetic promotion rule here
That said, void main()
should be int main(int argc, char* argv[])
, or, at least, int main(void)
.
Upvotes: 1
Reputation: 16607
if(a>b)
In this a
is unsigned int
and b
is signed int
, so due to implicit conversion , b
will be converted to unsigned int type
and b
will have a large value (no need to say, it will be greater than a
).
Therefore ,you get unexpected result.
According to C99- 6.3.1.8 Usual arithmetic conversions
[...]
3.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.
Upvotes: 0
Reputation: 234705
It's one of the type promotion rules: if one argument is an int
and the other an unsigned int
then the int
is promoted to an unsigned int
, adding UINT_MAX + 1 if necessary.
This happens prior to the comparison.
Upvotes: 0