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?
Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.
Detecting Overflow and Underflow in CIf both numbers are positive and the sum is negative, that means there is an overflow, so we return -1 else; if both numbers are negative and the sum is positive, that also means there is an overflow, so we return -1 else, no overflow.
There are two ways to get around this: Cast the numbers to a bigger integer type, then do the addition there, and check if the result is in the right range. Do the addition normally, then check the result (e.g. if (a+23<23) overflow).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With