Delphi-检测到Int64溢出错误

问题描述 投票:3回答:2

在Delphi中,如何检测Int64的溢出错误?

对于整数我们可以做:

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;

对于MyInt = Integer,行REF1给出异常,因此TryMaxTimes10返回false

但是如果我们将MyInt更改为MyInt = Int64,则REF1不会给出异常,并且TryMaxTimes10返回true

我了解{$Q+}的帮助没有特别提及Int64:... {$Q+} state, certain integer arithmetic operations ... are checked for overflow

问题:所以我的问题是,如何检测Int64的溢出错误?

((我正在使用Delphi7。在更新的Delphi版本中会发生同样的事情吗?)

delphi delphi-7
2个回答
3
投票

这是一个已知问题。参见http://qc.embarcadero.com/wc/qcmain.aspx?d=10185,而Andy在底部写的评论。

我的建议是创建一个函数(我没有编译也没有测试-只是一个例子):

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;

0
投票

此错误已在RAD Studio 10.2 Tokyo中修复。可以找到问题here(但必须先使用embarcadero帐户登录才能看到它)

© www.soinside.com 2019 - 2024. All rights reserved.