Signed operands must be tested before the addition is performed. Here is a safe addition function with 2 comparisons in all cases:
#include
int safe_add(int a, int b) {
if (a >= 0) {
if (b > INT_MAX - a) {
/* handle overflow */
} else {
return a + b;
}
} else {
if (b < INT_MIN - a) {
/* handle negative overflow */
} else {
return a + b;
}
}
}
If the type long long is known to have a larger range than type int, you could use this approach, which might prove faster:
#include
int safe_add(int a, int b) {
long long res = (long long)a + b;
if (res > INT_MAX || res < INT_MIN) {
/* handle overflow */
} else {
return (int)res;
}
}