I’m encountering a warning with the const keyword in C++ when using clang++ v. 17.0.1 or newer, with the flag -Winteger-overflow.
Here’s the code snippet:

int foo_const()
{
    const auto min = std::numeric_limits<int>::min(); // const keyword
    return - min; // warning: overflow in expression; result is -2147483648 with type 'int' [-Winteger-overflow]
}

int foo()
{
    auto min = std::numeric_limits<int>::min();   // no const keyword
    return - min; // no warning
}

In the foo_const function, I’m getting a warning about potential integer overflow. However, the same operation in the non-const foo function compiles without a warning.

I’d appreciate some help understanding why the const keyword triggers the overflow warning in this specific case.

5

When you use the const qualifier, the compiler will automatically replace uses of the variable with the initial value. When it tries to do this in the expression -min, the result is a value that’s outside the range of unsigned int.

In the version without const, the reference to min in the return statement is treated normally, rather than having the initial value substituted. So there’s no known overflow.