Coder3110
Coder3110

Reputation: 77

How to fix integer overflow warning

I have some code that checks if an integer is within the range [−2^31 + 1, 2^31 − 1]. However, during compilation, an integer overflow warning is thrown.

long int tmp_l = strtol(tokens[8].c_str(),NULL,10);

if (tmp_l >= ( (int32_t)-1 * ( ((int32_t)1<<31) - (int32_t)1) ) && 
        tmp_l <= ( ((int32_t)1 << 31) - (int32_t)1) ) {

    long int in_range = tmp_l;

} else {
    cerr << "ERROR: int not in range. Expected [(-2^31)-1, (2^31)-1]. ";
    cerr << "Found: " << tmp_l << endl;
}
main.cpp:93:51: warning: integer overflow in expression [-Woverflow]
     if (tmp_l >= ((int32_t)-1 * (((int32_t)1<<31) - (int32_t)1) ) &&
                                  ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~

The code compiles fine and I have not seen a runtime error related to this warning. Where am I going wrong?

Upvotes: 0

Views: 478

Answers (1)

eerorika
eerorika

Reputation: 238281

Where am I going wrong?

2^31 - 1 is the largest integer representable by a 32 bit signed integer. Therefore the result of operation 1 << 31, which is 2^31 is outside the range of representable values.

The behaviour of signed overflow is undefined.

How to fix

You could use this instead:

if (tmp_l >= std::numeric_limits<int32_t>::min() + 1
 && tmp_l <= std::numeric_limits<int32_t>::max()

Upvotes: 5

Related Questions