How to catch integer overflow in C ++?

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

I searched the site but did not find a good way to do this.

So ... any thoughts?

+4
source share
3 answers

As others said, if the result is different from both operands, two overflows occurred with addition.

The converse is also true. An overflow with two additions cannot occur if the operands are not the same sign (negative or non-negative), and the result is the opposite.

I personally prefer a simpler 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 signature overflow / underflow and unsigned, and it’s much easier to see what happens.

In addition, integral signed overflow in C ++ is not guaranteed by wrapping, since arithmetic with two additions is not required. A signed integer overflow can even crash, although this is unlikely. Thus, from the point of view of the language, it is better to stop the overflow before it occurs. C ++ 03 Β§5 / 5:

If during the evaluation of an expression the result is not determined mathematically or not in the range of representable values ​​for its type, the behavior is undefined if such an expression is not a constant expression (5.19), in which if the program is poorly formed. [Note: most existing C ++ implementations ignore whole overflows ....]

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

+6
source

__ asm jno notoverflow;

__ asm jo overflow.

Using asm here is more convenient.

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

Result: crowded

0
source

In order for an overflow to occur, both operands must be of the same character. If the sum of the operands is different from the operands, then overflow occurs.

 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 ) ); } 
-1
source

All Articles