警告C26451:算术溢出

Ela*_*ler 8 c++ warnings visual-c++

我该如何解决这些警告?

// 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;  }
Run Code Online (Sandbox Code Playgroud)

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; }
Run Code Online (Sandbox Code Playgroud)

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).

dou*_*oug 7

我相信这是VS2019中的错误

例如,这会产生警告

double test2(int n)
{
     return 4.0 * (n - 1);
}
Run Code Online (Sandbox Code Playgroud)

但这不是

int test2a(int n)
{
    return 4 * (n - 1);
}
Run Code Online (Sandbox Code Playgroud)

然而,后者的不确定行为的风险要大得多。乘以4会大大增加UB的风险,因为大量n会产生UB

可以说,要设置警告,警告所有对int的算术运算实际上都将很高。

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

警告C26454:算术溢出:'-'操作在编译时产生负无符号结果(io.5)

  • 这不是一个错误。请参阅讨论和接受的答案[此处](/sf/ask/4151589571/) (2认同)
  • @user11748261 接受的答案被删除了吗?现在还没有公认的答案。 (2认同)

120*_*arm 6

警告告诉您,在转换为结果(较大)类型之前,您的计算可能会溢出原始(较小)类型。在第一种情况下,如果vMIN_INT (-2 31 ),减法将下溢,导致未定义行为(可能是一个很大的正数),然后将存储在midiNote. 为避免出现警告,请先转换为较大的类型:

midiNote = double(v) - 48;
Run Code Online (Sandbox Code Playgroud)

同样对于您的第二个示例。

虽然您可以知道setMidiNote不会使用会出现此问题的值调用 ,但编译器不知道并发出此警告以提醒您潜在的问题。

  • @1201ProgramAlarm 当然,但是简单的表达式“I+1”也可以产生 UB。`4.0*(v-1)` 与 `4.0*(v+1)` 甚至只是 `v+1` 一样是一个问题,它会产生分散注意力的噪音,因为任何 C++ 用户都非常清楚 int 溢出问题,并且对它们进行强制转换以表明程序员承担防止 UB 的责任是荒谬的。 (3认同)
  • @1201ProgramAlarm 这是 VS2019 弹出的一个问题,它打开了核心指南检查。以前,它是实验性的。可以关闭该特定警告。请参阅我的答案和其中的链接。它使我的大部分代码都带有波浪线,因为我经常需要使用 double 来缩放 int 操作。 (3认同)
  • 您可以通过“#pragma warning (disable : 26451)”禁用警告。 (2认同)