c++ - 警告 C4307 : '*' : integral constant overflow

标签 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)

Sample code :

#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/

相关文章:

c++ - push_back 如何在 STL vector 中实现?

c++ - 为什么我的发布版本仍在寻找调试 DLL (MSVCR110D.dll)?

c++ - 如何将C++程序设置为在Windows启动时自动启动?(通过Windows Service解决方案)

c++ - 用于无损压缩一系列屏幕截图的适当图像文件格式

c++ - 在字符串数组中添加单词

c++ - c++ 类中的 static const 和 const 变量在存储方面有区别吗

c++ - 将屏幕截图位图转换为内存中的 jpeg

c++ - 给定 C++ 中的列变换右上三角矩阵

c++ - CreateBuffer 抛出 "Access violation reading location"

.net - 由于 2 秒超时,并非所有 native 全局变量都在混合模式 .Net 应用程序中被破坏