c++ - 整数转换问题

标签 c++ integer type-conversion uac

int left = std::numeric_limits<int>::min();
int right = -1;
//the code below instead of give one more than int_max gives: 18446744071562067968
unsigned long long result = left * right;

我已经尝试查找 UAC,但即使根据 UAC 规则,这也应该会产生正确的输出。知道为什么结果不正确吗?

最佳答案

将带符号的 2 的补码 int 的最小值乘以 -1 是未定义的行为,因为结果超出了类型的范围。

在这种情况下,您的输出与 -2147483648 的结果一致,即溢出似乎已经环绕。您不能依赖有符号类型的环绕,只能依赖无符号类型。

将计算结果赋值给 unsigned long long 不会改变执行计算的类型。只要你做乘法,你就输了。因此,将其中一个操作数转换为 unsigned long long before 乘法。

关于c++ - 整数转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13526966/

相关文章:

c - C 中从 16 位到 32 位的符号扩展

c++ integer->std::string 转换。简单的功能?

mysql - mysql中autoincrement能产生的最大ID号是多少

java - 缩小类型转换 : Why is assignment of int to a byte in a declaration allowed?

c# - 从字符串到用户定义类型的类型转换

将 malloc() 转换为 calloc()

c++ - 删除指针时堆损坏错误

c++ - 错误 : no match for ‘operator<’ when I stream to cout

c++ - 将 vector 以不匹配的大小加载到AVX2寄存器中

c++ - Node.js 插件对象销毁