Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Detect Int64 Overflow Error

In Delphi how can I detect overflow errors for Int64?

For Integers we could do:

type
MyInt = Integer; //Int64

function TryMaxTimes10(out Res: MyInt): boolean;
var
  a, b: MyInt;
begin
  {$Q+}
  try
    a := High(MyInt);
    b := 10;
    Res := a * b; //REF1
    Result := True; 
  except
    Result := False;
  end;
  {$Q-}
end;

For MyInt = Integer, line REF1 gives an exception and so TryMaxTimes10 returns false.

But if we change MyInt to MyInt = Int64, then REF1 does not give an exception and TryMaxTimes10 returns true!

I understand that the help for {$Q+} does not specifically mention Int64: ... {$Q+} state, certain integer arithmetic operations ... are checked for overflow.

QUESTION: So my question is, how can we detect overflow errors for Int64?

(I'm using Delphi 7. Does the same thing happen in newer versions of Delphi?)

like image 795
mas Avatar asked May 25 '26 00:05

mas


1 Answers

This is a known issue. See http://qc.embarcadero.com/wc/qcmain.aspx?d=10185, and the comments Andy wrote at the bottom.

My suggestion would be to create a function (I did not compile nor test this - just an example):

function Foo(A, B : Int64) : Int64;
var bNeg : boolean;
begin
  // Do we expect a negative result?
  bNeg := ((a < 0) xor (b < 0));
  // Get the real result
  Result := a * b;
  // If the result is wrong, raise an error
  if ((Result < 0) xor bNeg) then begin
    // Raise EOverFlow
  end;
end;
like image 80
Paul Avatar answered May 26 '26 19:05

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!