If you are sure you are using two's complement signed integers, then you can check the following: Two positive numbers added must give a positive result and two negative numbers added must give a negative result. It's impossible in only one sum to get two overflows, so if you are adding positive numbers, an overflow will arrive when your result is negative for the first time.
Either case, if you want your code to be portable, then the recommendation is to do something similar to this:
#include <limits.h>
...
if ((a > 0 && b > 0 && MAX_INT - a > b) ||
(a < 0 && b < 0 && MIN_INT - a < b)) {
/* OVERFLOW OF a + b WILL OCCUR */
...
}
if signs of operands are different it is impossible for a + b
to be greater than a
or b
in absolute value, so it is impossible for an overflow to happen.
For unsigned
s you have a similar approach (while you save half of the test, as operands can be only positive) but this time the first way is valid always (as standard says unsigned addition is considered a sum module 2^n
where n
is the wordsize in bits) and in that case you can make the sum and later check if the result is less than any of the operands (if both are positive, sum must be larger than or equal than any of the operands):
unsigned a, b;
...
unsigned sum = a + b;
if (sum < a || sum < b) {
/* OVERFLOW ON a + b HAS HAPPENED */
...
}
You have also to check for integer multiplication overflow. If a
and b
are to be multiplied, then a*b
can overflow. But this time the problem goes further, as overflow can occur more than once, and you cannot do it a posteriori. In that case you can have overflow with equal or different signs, as you are adding a
times b
(and b
has the same sign as itself) if both signs are equal the product will be positive, and overflows will occur
if (MAX_INT/b < a) { /* overflow */ }
if signs are different, the product should be negative, and then
if (MIN_INT/b < a) { /* overflow */ }
if one of the numbers is 0, then no overflow occurs on multipliying, as the result is 0.