开发者

How to catch integer overflow in C++? [duplicate]

开发者 https://www.devze.com 2023-04-05 06:00 出处:网络
This question already has answers here: How do I detect unsigned integer ov开发者_如何学JAVAerflow?
This question already has answers here: How do I detect unsigned integer ov开发者_如何学JAVAerflow? (30 answers) Closed 5 years ago.

I have a sum() function. I need to catch all overflow.

I searched website but didn't find a good way to do so.

So...any thoughts?


As others have said, if the result is a different sign than both operands, two's complement signed overflow occurred.

The converse is also true. Two's complement signed overflow cannot occur unless the operands are the same sign (negative or non-negative) and the result is the opposite.

Still, personally, I prefer a more straightforward approach:

int_type a = 12356, b = 98765432;
if ( b > 0 && a > std::numeric_limits< int_type >::max() - b )
    throw std::range_error( "adding a and b would cause overflow" );

if ( b < 0 && a < std::numeric_limits< int_type >::min() - b )
    throw std::range_error( "adding a and b would cause underflow" );

int_type c = a + b;

This will catch both signed and unsigned overflow/underflow, and it is much easier to see what is happening.

Moreover, integral signed overflow in C++ is not guaranteed to wrap around, since two's complement arithmetic is not required. Signed integer overflow can even crash, although it is unlikely. So in terms of the language, it's best to stop overflow before it occurs. C++03 §5/5:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined, unless such an expression is a constant expression (5.19), in which case the program is ill-formed. [Note: most existing implementations of C++ ignore integer overflows. …]

See also the Boost Numeric Conversion library, although I'm not sure it can do anything for this problem that std::numeric_limits can't.


In order for an overflow to occur, both operands must be the same sign. If the sum of the operands is a different sign than the operands, then an overflow occurred.

bool overflow( int a, int b )
{
    bool op_same_sign = ( a < 0 ) == ( b < 0 );
    bool sum_diff_sign = ( a < 0 ) != ( a + b < 0 );
    return op_same_sign && sum_diff_sign;
}

More concisely...

bool overflow( int a, int b )
{
    return ( ( a < 0 ) == ( b < 0 ) && ( a + b < 0 ) != ( a < 0 ) );
}


__asm jno notoverflow;

__asm jo overflow.

Using asm is more convenient here.

    int main()
    {
        int x = 2147483647;
        x++;
        __asm jo overflowed;
        printf("Not Overflow\n");
        if(0)
        {
            overflowed:
            printf("Overflowed!\n");
        }
        return 0;
    }

Result: Overflowed

0

精彩评论

暂无评论...
验证码 换一张
取 消