Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 550
Daniele Pallastrelli Avatar asked Aug 30 '25 16:08

Daniele Pallastrelli


2 Answers

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

like image 89
Barmar Avatar answered Sep 02 '25 06:09

Barmar


Short answer: the compiler is just not smart enough. Both functions result in the same UB.

like image 24
HolyBlackCat Avatar answered Sep 02 '25 06:09

HolyBlackCat