如何解决这些警告?
// 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 的代码分析规则集编辑器中禁用此警告的方法。
但是,从 VS2022 开始,Microsoft 不再为此生成波形曲线 C26451 警告。它也不会出现在 -Wall 下。他们显然看到了曙光。
关于c++ - 警告 C26451 : Arithmetic overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995817/