无符号和有符号整数

Unsigned and Signed Integers

如果我的编译器使用 2 字节 short 和 4 字节 int,为什么我的代码的最后两行输出不同?

我知道 x + y 溢出了 short 类型。但是最后两行不同是因为 math 至少有 int 精度,你可以打印出大值还是因为 z 自动转换为 unsigned int 来打印它?

#include <iostream>
using std::cout; using std::endl;

int main() {
    unsigned short x = 65'535;
    unsigned short y = 1;
    unsigned short z = x + y;
    cout << x << endl;
    cout << y << endl;
    cout << z << endl;
    cout << x + y << endl;
}

请注意,对于 cout << x + y,您将直接打印出 int;对于 arithmetic operator, before computation their operands will be integral promotioned,因此 x + y 的结果将是 int.

If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion.

另一方面,zunsigned short;当 x + y 的结果(即 int)被分配给 z 时,执行隐式转换(并发生溢出)。