lnt-arithmetic-overflow

算术表达式在转换为更宽的类型之前可能会溢出。

在 C 和 C++ 中,算术运算是使用最宽的操作数类型进行求值的,而不使用为结果赋予的类型的宽度。 当结果转换为更宽的类型时,它指示开发人员预计此运算可能溢出更窄的操作数类型。

lnt-arithmetic-overflow 检查是由 C/C++ 代码样式选项中的“算术溢出”设置控制的。 有关如何更改此设置的信息,请参阅配置 Linter

示例

#include <cstdint>

void overflow(int a, int b) {
    int64_t mul = a * b;      // Flagged: 32-bit operation may overflow.
    int64_t shift = a << 34;  // Flagged: Shift would overflow.

    int64_t mul2 = mul + b;   // OK: 'mul' is 64-bit so the addition expression is
                              // evaluated using 64-bit operations.
}

如何解决此问题

Linter 建议的解决方法是显式加宽其中一个操作数。 随后,整个表达式将以更宽的结果类型进行求值,如以下示例中所示:

void overflow(int a, int b) {
    int64_t mul = static_cast<int64_t>(a) * b;
    int64_t shift = static_cast<int64_t>(a) << 34;
}

请参阅

适用于 C++ 的 IntelliSense 代码 Linter 概述