减去无符号整数的编译器警告(或静态分析)?

Compiler warning (or static analysis) for subtraction of unsigned integers?

考虑以下程序:

#include <iostream>

int main()
{
    unsigned int a = 3;
    unsigned int b = 7;

    std::cout << (a - b) << std::endl;  // underflow here!

    return 0;
}

在以 std::cout 开头的行中发生了下溢,因为 a 小于 b 所以 a-b 小于 0,但是由于 ab 是无符号的 a-b.

也是

当我尝试计算两个无符号整数的差值时,是否有编译器标志(针对 G++)向我发出警告?

现在,有人可能会争辩说 overflow/underflow 可以在使用任何运算符的任何计算中发生。但我认为将运算符 - 应用于 unsigend int 更危险,因为对于无符号整数,此错误可能会在非常低(对我而言:“更常见”)数字时发生。

发现此类问题的(静态分析)工具也很棒,但我更喜欢编译器标志和警告。

GCC 不 (afaict) 支持它,但 Clang's UBSanitizer 有以下选项 [emphasis 我的]:

-fsanitize=unsigned-integer-overflow: Unsigned integer overflow, where the result of an unsigned integer computation cannot be represented in its type. Unlike signed integer overflow, this is not undefined behavior, but it is often unintentional. This sanitizer does not check for lossy implicit conversions performed before such a computation