No, your 2nd code isn’t correct, but you are close: if you set
int half = INT_MAX/2;
int half1 = half + 1;
the result of an addition is INT_MAX
. (INT_MAX
is always an odd number). So this is valid input. But in your routine you will have INT_MAX - half == half1
and you would abort. A false positive.
This error can be repaired by putting <
instead of <=
in both checks.
But then also your code isn’t optimal. The following would do:
int add(int lhs, int rhs)
{
if (lhs >= 0) {
if (INT_MAX - lhs < rhs) {
/* would overflow */
abort();
}
}
else {
if (rhs < INT_MIN - lhs) {
/* would overflow */
abort();
}
}
return lhs + rhs;
}
To see that this is valid, you have to symbolically add lhs
on both sides of the inequalities, and this gives you exactly the arithmetical conditions that your result is out of bounds.