无符号和有符号整数

时间:2017-05-26 00:56:30

标签: c++ integer-promotion

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

我认为x + y溢出short类型。但是最后两行是不同的,因为数学至少具有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;
}

1 个答案:

答案 0 :(得分:3)

请注意,对于cout << x + y,您需要直接打印int;对于arithmetic operator,在计算之前,其操作数将为integral promotion,因此x + y的结果将为int

  

如果传递给算术运算符的操作数是整数或无范围的枚举类型,那么在任何其他操作之前(但在左值到右值的转换之后,如果适用),操作数将进行整数提升。

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