Logo

Programming-Idioms

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

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.

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;
function AddingWillOverFlow(x,y: Integer): Boolean;
begin
  Result := (x > 0) and (y > 0) and (x > (MaxInt-y));
end;

MaxInt is a predefined constant holding the largest possible signed integer on the current platform.

PROBLEM: this doesn't detect negative overflow.
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