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

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.

fn adding_will_overflow(x: usize, y: usize) -> bool {
    x.checked_add(y).is_none()
}
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;
import core.checkedint;
bool addingWillOverflow(int x, int y)
{
    bool result;
    core.checkedint.adds(x, y, result);
    return result;
}
addingWillOverflow x y = y > maxBound - x
function AddingWillOverFlow(x,y: Integer): Boolean;
begin
  Result := (x > 0) and (y > 0) and (x > (MaxInt-y));
end;
function AddingWillOverFlow(x,y: Integer): Boolean;
begin
  Result := ((x > 0) and (y > 0) and (x > (High(Integer)-y))) or
            ((x < 0) and (y < 0) and ((Low(Integer)-x) > y));
end;
def addingWillOverflow(x,y):
	return False
def addingWillOverflow(x,y)
  false
end

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

deleplace

Related idioms