编译器向我显示以下代码的以下警告:
Warning: W1036 Variable 'Address' might not have been initialized
代码(基于实际代码的MVCE代码段):
function DoFoo(): Integer;
var
i: Integer;
Address, Bar: Cardinal;
begin
for i := 1 to 5 do
begin
try
Address := Hex2CardPos(IntToStr(i));
except on EConvertError do
continue;
end;
Bar := Address + 42; // "Warning: Address might not have been initialized"
end;
Result := 42;
end;
如您所见,Address
是:
Hex2CardPos()
Hex2CardPos()
抛出错误,并立即跳过循环迭代。我试图通过在循环的开头添加一个无用的Address := 0;
来解决这个问题,但是警告只是替换为另一个:
Hint: H2077 Value assigned to 'Address' never used.
这是编译器错误还是警告有实质内容?
答案 0 :(得分:8)
问题在于您的代码。 "Bar"
分配必须在try except块中,因为当发生异常时你不想分配"Bar"
function DoFoo(): Integer;
var
i: Integer;
Address, Bar: Cardinal;
begin
for i := 1 to 5 do
begin
try
Address := Hex2CardPos(IntToStr(i));
Bar := Address + 42;
except on EConvertError do
continue;
end;
end;
Result := 42;
end;
顺便说一下,这段代码的"H2077 Value assigned to 'Bar' never used"
是正确的。