0

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?

0

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.