program CheckOverflow;
function AdditionWillOverflow(a, b: Integer): Boolean;
begin
if (b > 0) and (a > MaxInt - b) then
AdditionWillOverflow := True // Positive overflow
else if (b < 0) and (a < Low(Integer) - b) then
AdditionWillOverflow := True // Negative overflow
else
AdditionWillOverflow := False;
end;
var
x, y, z: Integer;
begin
x := MaxInt - 5;
y := 10;
if AdditionWillOverflow(x, y) then
writeln('* Positive overflow will occur.')
else
writeln('* Sum: ', x + y);
x := Low(Integer) + 5;
y := -10;
if AdditionWillOverflow(x, y) then
writeln('** Negative overflow will occur.')
else
writeln('** Sum: ', x + y);
x := 17;
y := 24;
if AdditionWillOverflow(x, y) then
writeln('*** Overflow will occur.')
else
writeln('*** Sum: ', x + y);
end.
(*
run:
* Positive overflow will occur.
** Negative overflow will occur.
*** Sum: 41
*)