views:

288

answers:

3

Possible Duplicate:
Best way to detect integer overflow in C/C++

There's (1):

// assume x,y are non-negative
if(x > max - y) error;

And (2):

// assume x,y are non-negative
int sum = x + y;
if(sum < x || sum < y) error;

Whichs is preferred or is there a better way.

+3  A: 

You only have to check one of them. If x + y overflows, it will be less than both x and y. Hence:

int sum = x + y;
if (sum < x) error;

should be sufficient.

The following site has a bunch of stuff about integer overflow:

http://www.fefe.de/intof.html

If you want to handle negative numbers, it can be expanded:

int sum = x + y;
if (y >= 0) {
   if (sum < x) error;
} else {
   if (sum > x) error;
}
clahey
What if `y` is negative?
Fred Larson
The original poster specified non-negative integers, but I've added code to handle negative numbers.
clahey
This isn't correct - once `x + y` has overflowed, the program has undefined behaviour. You *have* to check before you actually execute the overflowing operation - just as you do for integer division by zero.
caf
+1  A: 

You can really only check for overflow with unsigned integers and arithmatic:

unsigned a,b,c;
a = b + c;
if (a < b) {
    /* overflow */
}

The behavior of overflow with signed integers is undefined in C, but on most machines you can use

int a,b,c;
a = b + c;
if (c < 0 ? a > b : a < b) {
    /* overflow */
}

This won't work on machines that use any kind of saturating arithmetic

Chris Dodd
+3  A: 

Integer overflow is the canonical example of "undefined behaviour" in C (noting that operations on unsigned integers never overflow, they are defined to wrap-around instead). This means that once you've executed x + y, if it overflowed, you're already hosed. It's too late to do any checking - your program could have crashed already. Think of it like checking for division by zero - if you wait until after the division has been executed to check, it's already too late.

So this implies that method (1) is the only correct way to do it. For max, you can use INT_MAX from <limits.h>.

If x and/or y can be negative, then things are harder - you need to do the test in such a way that the test itself can't cause overflow.

if ((y > 0 && x > INT_MAX - y) ||
    (y < 0 && x < INT_MIN - y))
{
    /* Oh no, overflow */
}
else
{
    sum = x + y;
}
caf