When you use an arithmetic operator, the operands go through two conversions.
Integer promotions: If int
can represent all values of the type, then the operand is promoted to int. This applies to both short
and unsigned short
on most platforms. The conversion performed on this stage is done on each operand individually, without regard for the other operand. (There are more rules, but this is the one that applies.)
Usual arithmetic conversions: If you compare an unsigned int
against a signed int
, since neither includes the entire range of the other, and both have the same rank, then both are converted to the unsigned
type. This conversion is done after examining the type of both operands.
Obviously, the "usual arithmetic conversions" don‘t always apply, if there are not two operands. This is why there are two sets of rules. One gotcha, for example, is that shift operators <<
and >>
don‘t do usual arithmetic conversions, since the type of the result should only depend on the left operand (so if you see someone type x << 5U
, then the U
stands for "unnecessary").
Breakdown: Let‘s assume a typical system with 32-bit int and 16-bit short.
int a = -1; // "signed" is implied
unsigned b = 2; // "int" is implied
if (a < b)
puts("a < b"); // not printed
else
puts("a >= b"); // printed
int
or unsigned int
, no promotions are done.int
can‘t represent all possible values of unsigned
, and unsigned
can‘t represent all possible values of int
, there is no obvious choice. In this case, both are converted to unsigned
.if (4294967295u < 2u)
, which is false.Now let‘s try it with short
:
short c = -1; // "signed" is implied
unsigned short d = 2;
if (c < d)
puts("c < d"); // printed
else
puts("c >= d"); // not printed
int
, both are promoted to int
.int
, so nothing is done.if (-1 < 2)
, which is true.Writing good code: There‘s an easy way to catch these "gotchas" in your code. Just always compile with warnings turned on, and fix the warnings. I tend to write code like this:
int x = ...;
unsigned y = ...;
if (x < 0 || (unsigned) x < y)
...;
You have to watch out that any code you do write doesn‘t run into the other signed vs. unsigned gotcha: signed overflow. For example, the following code:
int x = ..., y = ...;
if (x + 100 < y + 100)
...;
unsigned a = ..., b = ...;
if (a + 100 < b + 100)
...;
Some popular compilers will optimize (x + 100 < y + 100)
to (x < y)
, but that is a story for another day. Just don‘t overflow your signed numbers.
Footnote: Note that while
signed
is implied forint
,short
,long
, andlong long
, it is NOT implied forchar
. Instead, it depends on the platform.
原文地址:http://www.cnblogs.com/wangaohui/p/3832445.html