c++ - 警告 C26451 : Arithmetic overflow

标签 c++ visual-c++ warnings

如何解决这些警告?

// midiNote is a double as it is used in floating point equation
// v is int because that's informative that the function wants whole numbers
void setMidiNote(int v) { midiNote = v-48;  }

Warning C26451 Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '-' to avoid overflow (io.2).

// input should be 0 to 10 integer, and dank will be odd integers only
// dank is a double, it is ultimately used in a floating point equation
void setDarkIntensity(int v) { dank = v * 2 + 1; }

Warning C26451 Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '*' to avoid overflow (io.2).

Warning C26451 Arithmetic overflow: Using operator '+' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '+' to avoid overflow (io.2).

最佳答案

我相信这是 VS2019 中的一个错误。它不再在 VS2022 中被标记。

例如这会产生警告

double test2(int n)
{
     return 4.0 * (n - 1);
}

但这并不

int test2a(int n)
{
    return 4 * (n - 1);
}

然而,后者出现未定义行为的风险要大得多。乘以 4 会大大增加 UB 的风险,因为大量的 n 集合将产生 UB。多么伟大?嗯,在第一个示例中,大约 40 亿个可能的值中只有一个可能的 n 值发生了溢出。在第二个中,大约有 30 亿个 n 会上溢/下溢。为什么?因为如果每个比加 0 或乘 1 更复杂的表达式都被标记,那么整数运算将是不可能的,因为它可能会溢出。

可以说,将警告设置为高实际上任何对整数的算术运算都会被警告。

这个答案展示了在 VS 2019 的代码分析规则集编辑器中禁用此警告的方法。

Warning C26454: Arithmetic overflow: '-' operation produces a negative unsigned result at compile time (io.5)

但是,从 VS2022 开始,Microsoft 不再为此生成波形曲线 C26451 警告。它也不会出现在 -Wall 下。他们显然看到了曙光。

关于c++ - 警告 C26451 : Arithmetic overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995817/

相关文章:

c++ - 如何在 Windows XP 上为 Qt 4.7 正确构建 OpenCV 2.3.1?

c - msvc中的按位运算符左移与linux gcc不同?

ruby-on-rails - 为什么我在尝试安装 RVM 时收到警告?

c++ - 从 MSVC 输出生成 Makefile 依赖项

visual-c++ - wxwidget 2.9.1在Visual C++上编译,错误MSB 3073 : The command xcopy

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c - 不使用数组时会显示数组下标类型为 'char' 的警告

c++ - 获取 C++ 引用的地址以传递给指针

c++ - QtCreator 4.1.0 不显示 MainWindow 表单编辑器的 webengineview(QT 5.7)

C++ CMake 链接错误 : LNK1181: Cannot open input file "x.lib"