如何摆脱被“continue”混淆的编译器警告?

How to get rid of compiler warning confused by `continue`?

编译器向我显示以下代码的以下警告:

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 是:

  1. 分配给Hex2CardPos()
  2. 的结果
  3. Hex2CardPos() 抛出错误并立即跳过循环迭代。

我试图通过在循环开头添加一个无用的 Address := 0; 来解决这个问题,但随后警告被另一个替换:

Hint: H2077 Value assigned to 'Address' never used.

这是编译器错误还是警告有实质内容?

问题出在您的代码中。 "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" 是正确的。