警告C26451:算术溢出 [英] Warning C26451: Arithmetic overflow
问题描述
我该如何解决这些警告?
// midiNote是它的两倍在浮点方程
中使用// // v是int的,因为这说明该函数需要整数
void setMidiNote(int v){midiNote = v-48; }
警告C26451算术溢出:在4字节值上使用运算符'-',然后强制转换结果到8字节的值。在调用运算符'-'之前,将值转换为更宽泛的类型,以避免溢出(io.2)。
//输入应为0到10的整数,并且dank仅是奇数整数
// dank是双精度型,最终将其用于浮点方程
void setDarkIntensity(int v) {dank = v * 2 +1; }
警告C26451算术溢出:在4字节值上使用运算符'*',然后强制转换结果到8字节的值。在调用运算符'*'之前,将值转换为更宽泛的类型,以避免溢出(io.2)。字节值,然后将结果转换为8字节值。在调用运算符'+'之前,将值转换为更宽泛的类型,以避免溢出(io.2)。
是VS2019中的错误
例如,这会产生警告
double test2(int n)
{
返回4.0 *(n-1);
}
但这不是
int test2a(int n)
{
返回4 *(n-1);
}
但是,后者的不确定行为的风险更大。乘以4会大大增加UB的风险,因为大量n会产生UB
可以这么说,警告是实际上对int进行任何算术运算都很高将被警告。
此答案显示了一种在VS 2019中的代码分析规则集编辑器中禁用此警告的方法。
警告C26454:算术溢出:'-'运算在编译时(io.5)产生负的无符号结果
How do I solve these 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).
I believe this is a bug in VS2019
For instance this produces the warning
double test2(int n)
{
return 4.0 * (n - 1);
}
But this doesn't
int test2a(int n)
{
return 4 * (n - 1);
}
Yet, the risk of undefined behavior is much greater for the latter. Multiplying by 4 greatly increases the risk of UB since a far large set of n's will produce UB
Arguably, for a warning to be set that high virtually any arithmetic operation on ints would be warned.
This answer shows a way to disable this warning in VS 2019 in the code analysis rule set editor.
这篇关于警告C26451:算术溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!