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).
我相信这是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)
警告告诉您,在转换为结果(较大)类型之前,您的计算可能会溢出原始(较小)类型。在第一种情况下,如果vMIN_INT (-2 31 ),减法将下溢,导致未定义行为(可能是一个很大的正数),然后将存储在midiNote. 为避免出现警告,请先转换为较大的类型:
midiNote = double(v) - 48;
Run Code Online (Sandbox Code Playgroud)
同样对于您的第二个示例。
虽然您可以知道setMidiNote不会使用会出现此问题的值调用 ,但编译器不知道并发出此警告以提醒您潜在的问题。