如何避免 Microsoft C26451(算术溢出)警告

时间:2021-04-27 05:59:42

标签: c++ visual-studio-2015 overflow

在我的示例中,如何针对 Microsoft C26451(算术溢出)警告进行防御性编码?我觉得这应该很容易解决。好郁闷!

    // Linear interpolation
    // target  - the target point, 0.0 - 1.0
    // x...    - two values {X1} {X2}
    inline static double Linear(float target, double x1, double x2) {
        return (target * x2) + ((1.0 - (double)target) * x1);
    }

我通读了 Arithmetic overflow: Using operator '*' on a 4 byte value then casting the result to a 8 byte value,但似乎无法解决我的 C26451 警告:“算术溢出:在 4 字节值上使用运算符‘-’,然后将结果转换为 8 字节值。转换值在调用运算符 '-' 之前改为更宽的类型以避免溢出 (io.2)。

我该怎么做才能消除警告?

有关编译错误的 Microsoft 文档并没有真正帮助。 https://docs.microsoft.com/en-us/cpp/code-quality/c26451

1 个答案:

答案 0 :(得分:1)

编译器警告没有意义,较新的 Visual Studio 版本不会给出相同的警告。我只会为此行禁用它:

inline static double Linear(double target, double x1, double x2) {
    #pragma warning( push )
    #pragma warning( disable : 26451 )
    return (target * x2) + ((1.0 - target) * x1);
    #pragma warning( pop )
}
相关问题