Signed integer in C
#include<stdio.h>
int main()
{
unsigned int a=6;
int b=-20;
开发者_如何学运维 (a+b>6)?puts(">6"):puts("<=6");
return 0;
}
The above code outputs >6
. But I got a doubt. b=-20
will hold a negative value (-18
)
after doing the 2's complement as it's a signed integer. So it should output <=6
but its
giving an output as >6
.
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.
Basically, in the case of your example code, unsigned int
and int
have 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)
The answer is to be found in section "6.3.1.8 Usual arithmetic conversions" of the C99 standard, which favors the unsigned type when a signed type and an unsigned one are passed to a binary operator (the reality is much more subtle than that).
See this blog post for another example of working through the rules in 6.3.1.8.
You are mixing signed and unsigned integers in your code. That is a bad thing. Try the following snippet:
int main()
{
unsigned int a = 0;
int b=-20;
printf("(a + b) = %f", (a + b));
return 0;
}
Don't mix signed and unsigned integers because the compiler will do a silent conversion just when you don't want it to.
精彩评论