在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版本中会发生同样的事情吗?)
这是一个已知问题。参见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;
此错误已在RAD Studio 10.2 Tokyo中修复。可以找到问题here(但必须先使用embarcadero帐户登录才能看到它)