# Programming-Idioms

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.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
function Adding_Will_Overflow (X, Y : Integer) return Boolean is
begin
return X > 0 and Y > 0 and X > Integer'Last - Y;
#include <limits.h>
#include <stdbool.h>
bool addingWillOverflow(int x, int y) {
return ((x > 0) && (y > INT_MAX - x)) ||
((x < 0) && (y < INT_MIN - x));
}
#include <limits>
bool addingWillOverflow(int x, int y) {
return ((x > 0) && (y > std::numeric_limits<int>::max() - x)) ||
((x < 0) && (y < std::numeric_limits<int>::min() - x));
}
{
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;
}
import core.checkedint;
{
bool result;
return result;
}
integer, intent(in) :: x, y
res = (x > 0 .and. y > huge(x) - x) .or. (x < 0 .and. y < huge(x) - x)
import "math"
func addingWillOverflow(x int, y int) bool {
if x > 0 {
return y > math.MaxInt-x
}
return y < math.MinInt-x
}
addingWillOverflow x y = y > maxBound - x
return x > 0 && y > 0 && x > Number.MAX_SAFE_INTEGER - y
}
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;
}
{
return (PHP_INT_MAX - \$y) > \$x;
}
begin
Result := ((x > 0) and (y > 0) and (x > (High(Integer)-y))) or
((x < 0) and (y < 0) and ((Low(Integer)-x) > y));
end;
begin
Result := (x > 0) and (y > 0) and (x > (MaxInt-y));
end;