对于以下代码,我得到了溢出,但遗憾的是我似乎无法理解原因。
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/