3

我很困惑。例子:

int x=-1; 
unsigned y=0;
(x<y) ----> false

int8_t x=-1;
unint8_t y=0;
(x<y) ----> true

此外,编译器会在第一次比较时发出警告,但不会在第二次比较时发出警告。似乎对于

  • (int vs unsigned) - int 提升为 unsigned
  • (intN_t vs uintN_t) - uintN_t 提升为 intN_t

为什么会有这种行为?就像……真的吗?

4

2 回答 2

3

Whenever you apply any binary arithmetic operator (including comparisons) to a pair of numeric types which are both shorter than int, C converts both operands to int before performing the operation.

Whenever you apply any binary arithmetic operator to a pair of numeric types which are the same size, mismatched in signedness, and not shorter than int, C converts the signed operand to unsigned before the operation.

These are two of the "integer promotion" rules. They are not terribly intuitive, and they are probably not what one would do if one were designing C from scratch today, but they are what they are and we are stuck with them.

于 2013-05-02T16:57:01.537 回答
2

这是通常的整数转换的结果。

在第一种情况下,两个操作数的等级至少为int,并且具有相同的等级,因此它们被转换为无符号整数类型。

在第二种情况下,int8_tis char(它必须是,如果它存在的话),所以两个操作数都被提升为int. -1和都0可以在 中表示int,因此没有警告。

于 2013-05-02T16:56:48.490 回答