警告 C26451:算术溢出

新手上路,请多包涵

如何解决这些警告?

 // 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;  }

警告 C26451 算术溢出:对 4 字节值使用运算符“-”,然后将结果转换为 8 字节值。在调用运算符“-”之前将值转换为更广泛的类型以避免溢出 (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; }

警告 C26451 算术溢出:对 4 字节值使用运算符“*”,然后将结果转换为 8 字节值。在调用运算符 ‘*’ 之前将值转换为更广泛的类型以避免溢出 (io.2)。

警告 C26451 算术溢出:对 4 字节值使用运算符“+”,然后将结果转换为 8 字节值。在调用运算符“+”之前将值转换为更广泛的类型以避免溢出 (io.2)。

原文由 Elan Hickler 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.8k
1 个回答

尽早转换为您想要的数据类型,然后一直使用它:

 // 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 = static_cast<double>(v) - 48.0;  }

 // 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 = static_cast<double>(v) * 2.0 + 1.0; }

过去整数运算比浮点运算快得多,但在现代 CPU 上不再如此。

使用 2.0 而不是 2 强制将 v 转换为 double e06a779a6069c903b66e3

额外建议: 考虑验证调试版本中的任何假设。当您将来更改代码时,这将有助于避免打破这些假设。就像是:

 // 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)
{
    assert(v >= 0 && v <= 10);
    dank = static_cast<double>(v) * 2.0 + 1.0;
}

奖励建议 2: 如果这些函数不是类的一部分,我会将它们标记为 inline 以便优化器有更好的机会使用这些简单的函数来完成它的工作。如果它们是类定义的一部分,那么这已经隐式完成了。

原文由 Darrin Cullop 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题