How to check if integer multiplication will overflow in Pascal

1 Answer

0 votes
program CheckOverflow;

function MultiplyWillOverflow(x, y: Integer): Boolean;
begin
  if ((x and y) = 0) then
    MultiplyWillOverflow := False
  else
  begin
    if ((x > 0) and (y > 0)) or ((x < 0) and (y < 0)) then
      MultiplyWillOverflow := ((High(Integer) div Abs(x)) > Abs(y))
    else
      MultiplyWillOverflow := Abs(Low(Integer) div Abs(x)) > Abs(y);
  end;
end; 

var
  x, y, z: Integer;
begin
  x := MaxInt - 5;
  y := 10;
  if MultiplyWillOverflow(x, y) then
    writeln('* Positive overflow will occur.')
  else
    writeln('* Multiply: ', x * y);
  
  x := Low(Integer) + 5; 
  y := 10;
  if MultiplyWillOverflow(x, y) then
    writeln('** Negative overflow will occur.')
  else
    writeln('** Multiply: ', x * y);

  x := 17;
  y := 24;
  if MultiplyWillOverflow(x, y) then
    writeln('*** Overflow will occur.')
  else
    writeln('*** Multiply: ', x * y);
end.


  
(*
run:
  
* Multiply: 327620
** Multiply: -327630
*** Overflow will occur.
  
*)  


 



answered May 18, 2025 by avibootz
...