Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #85 Check if integer addition will overflow

Write boolean function addingWillOverflow which takes two integers x, y and return true if (x+y) overflows.

An overflow may be above the max positive value, or below the min negative value.

public boolean addingWillOverflow(int x, int y){
    boolean willOverFlow = false;
    if(x > 0 && y > 0){
        if(y > (Integer.MAX_VALUE - x)){
            willOverFlow = true;
        }
    }
    if(x < 0 && y < 0){
       if(y < (Integer.MIN_VALUE - x)){
           willOverFlow = true;
       }
    }
    return willOverFlow;
}

If both values are positive, make sure the difference between one and the MAX_VALUE is less than the other, otherwise they will overflow.
If both values are negative, make sure the difference between one and the MIN_VALUE is less than the other, otherwise they will underflow.
The case where one is negative and one is positive does not need to be checked as they will definitely not under or overflow in that scenario.
import static java.lang.Math.addExact;
import static java.lang.Math.subtractExact;
boolean willOverflow(int x, int y) {
    try {
        addExact(x, y);
        subtractExact(x, y);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}
function Adding_Will_Overflow (X, Y : Integer) return Boolean is
begin
   return X > 0 and Y > 0 and X > Integer'Last - Y;
end Adding_Will_Overflow;

PROBLEM: this doesn't detect negative overflow.

New implementation...
< >
deleplace