How to check if integer addition will overflow in Pascal

3 Answers

0 votes
program CheckOverflow;

var
  a, b, sum: Integer;
  maxValue: Integer;
begin
  a := MaxInt - 5;
  b := 10;
  maxValue := MaxInt;

  if (a > 0) and (b > 0) and (a > maxValue - b) then
  begin
    writeln('* Addition will overflow!');
  end
  else
  begin
    sum := a + b;
    writeln('*1 Sum: ', sum);
  end;

  a := -5;
  b := 10;
  maxValue := MaxInt;

  if (a > 0) and (b > 0) and (a > maxValue - b) then
  begin
    writeln('** Addition will overflow!');
  end
  else
  begin
    sum := a + b;
    writeln('** Sum: ', sum);
  end;

  readln;
end.


  
(*
run:
  
* Addition will overflow!
** Sum: 5
  
*)  

 



answered May 17, 2025 by avibootz
0 votes
program CheckOverflow;

var
  a, b: Integer;
  sum: LongInt;
begin
  a := MaxInt - 5;
  b := 10;

  sum := LongInt(a) + LongInt(b);
  if sum > High(Integer) then
  begin
    writeln('Integer overflow occurred (but LongInt can hold the result): ', sum);
  end
  else
  begin
    writeln('Sum (as Integer): ', Integer(sum));
  end;

  readln;
end.


  
(*
run:
  
Integer overflow occurred (but LongInt can hold the result): 32772
  
*)  


 



answered May 17, 2025 by avibootz
0 votes
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
  
*)  


 



answered May 17, 2025 by avibootz

Related questions

1 answer 278 views
1 answer 255 views
1 answer 265 views
1 answer 266 views
...