c++ - 奇怪的整数溢出逻辑

标签 c++ integer-arithmetic

对于以下代码,我得到了溢出,但遗憾的是我似乎无法理解原因。

std::int8_t smallValue         = -1;
unsigned int value             = 500;
std::uint8_t anotherSmallValue = 1;

auto test = smallValue * value * anotherSmallValue;

之后 test 是一个相当大的值。

谁能解释一下,这里发生了什么?

最佳答案

结果类型将为 unsigned int test here . smallValue * value smallValue 将转换为无符号,因此此表达式为 (unsigned)-1 * 500。但是,如果您使用 -Wsign-conversion 编译此代码 - 编译器会告诉您,您做了坏事。 link

关于c++ - 奇怪的整数溢出逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15834326/

相关文章:

c++ - 滥用逗号运算符来柯里化(Currying)函数参数

c++ - 如何使用 Boost log 设置每个日志源的严重性级别?

c++ - OpenGL- glDrawElements仅绘制第一个元素

c++ - 为什么 IEEE-754 float 不能在平台之间交换?

sql - 大查询 : How to represent integer of type Long in Bigquery?

java - 仅用整数运算实现算法,汽车的多个油耗率

仅使用整数常量表达式计算 sqrt(SIZE_MAX+1),以适应奇怪的 ABI

c++ - 用于碰撞检测实现的四叉树

c++ - 是否可以通过消除 >= 比较的需要,将有符号的双关符号输入无符号整数来加快边界检查?