7

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?

3
  • depends on what you are summing. provide code Commented Sep 16, 2011 at 23:05
  • Actually, the cross-referenced question is about any default data type, though it is certainly true that the primary example is about float rather than int in any of its various forms. The answers definitely cover some safe integer libraries though, and would therefore help the questioner. Commented Sep 17, 2011 at 0:02
  • See also: Best way to detect integer overflow in C/C++. Commented Sep 17, 2011 at 0:06

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You need to assert b is non-negative first, otherwise you run into UB again.
@BaummitAugen Thanks, fixed. There's a little subtlety here where I wanted the solution to be purely obvious…
Almost, but the second if is still wrong. If b is negative, std::numeric_limits< int_type >::min() + b is still UB.
@BaummitAugen Oh no, it's worse. The second one was backwards all along! Both need to use subtraction.
How about for the test case of (a * b) overflow?
-1

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

3 Comments

@Michael: The term integer underflow is often used to describe "overflowing" INT_MIN. Similarly std::numeric_limits< float >::min() is a very small value while std::numeric_limits< int >::min() is very large.
@Potatoswatter - and we both know that is incorrect. Though in this case, I was clearly incorrect :)
This is undefined behaviour.
-2

__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

2 Comments

Could you elaborate on this? How would I use it in practice?
#1. not portable, (this example only overflows on x86 32bit). #2 should write the function completely in assembler, mixing c and asm without completely knowing the target compiler can be dangerous, as this example, the compiler could insert code after the math that could reset the overflow flag (may work for gcc but fail for intel/llvm) and may change depending on flags into the compiler (bounds checking).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.