我在c++下编程时遇到了一件奇怪的事.这是关于 32bit
signed
数字的加法
(uint32)(SIN32_MIN * (-1)) //signed integer 4 bytes
给出:
warning C4307: '*' : integral constant overflow
SIN32_MIN
= -2147483648
。
最佳答案
如果将 INT32_MIN
乘以 -1
,您将溢出,因为 2147483648 不能用带符号的 32 位整数表示。
如果您试图获得 -1 * (-2147483648) = 2147483648
,请尝试这样做:(((uint32_t)(INT32_MAX)) + 1)
#include <stdint.h>
#include <stdio.h>
int main()
{
uint32_t n = static_cast<uint32_t>(INT32_MAX)+1;
printf("n: %u\n", n);
}
输出:
n: 2147483648
这会产生 no warnings with clang .
作为侧节点,出于类似原因,通常 INT32_MIN 未定义为 #define INT32_MIN -2147483648
。它通常被定义为 (-2147483647 - 1)
或类似的东西。
您也可以 do this instead : (uint32_t)(INT32_MIN * -1LL)
关于c++ - 警告 C4307 : '*' : integral constant overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43800499/