Warning C26451: Arithmetic overflow

醉酒当歌 提交于 2019-12-20 21:03:12

问题


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


回答1:


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.

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




回答2:


The warnings are telling you that there is a chance that your calculation will overflow the original (smaller) type before conversion to the result (larger) type. In the first case, if v is MIN_INT (-231), the subtraction will underflow, resulting in Undefined Behavior (likely a large positive number) that will then be stored in midiNote. To avoid the warning, convert to the larger type first:

midiNote = double(v) - 48;

Similarly for your second example.

While you can know that setMidiNote will not be called with values that will have this problem, the compiler doesn't know and issues this warning to alert you to the potential for a problem.



来源:https://stackoverflow.com/questions/55995817/warning-c26451-arithmetic-overflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!