Logo

Programming-Idioms

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

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.

bool addingWillOverflow(int x, int y)
{
  bool willOverflow = false;

  if (x > 0 && y > 0)
    if (y > (int.MaxValue - x)) willOverflow = true;

  if (x < 0 && y < 0)
    if (y < (int.MinValue - x)) willOverflow = true;

  return willOverflow;
}
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