Search code examples
c++compiler-warningsclang++

Integer overflow warning only when using const keyword


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.


Solution

  • 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 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.

    The compiler conceivably could detect that the variable is not reassigned between initialization and use in the return statement. But it apparently doesn't do that for the purpose of detecting errors like this (it might do it later in the optimizer).