Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The compiler shows me the following warning for the code below:

Warning: W1036 Variable 'Address' might not have been initialized

The code (an MVCE snippet based on real code):

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;

As you can see, Address is either:

  1. Assigned to the Result of Hex2CardPos()
  2. Hex2CardPos() throws an error and the loop iteration is immediately skipped.

I tried to fix this by adding a useless Address := 0; to the beginning of the loop, but then the warning is just replaced with another:

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

Is this a compiler bug or does the warning have substance?

like image 559
DBedrenko Avatar asked Feb 08 '23 15:02

DBedrenko


1 Answers

The problem is in your code. "Bar" assignation has to be in the try except block because when an exception happens you dont want assign "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;

Btw this code has a "H2077 Value assigned to 'Bar' never used" that's correct.

like image 187
Agustin Seifert Avatar answered Apr 28 '23 13:04

Agustin Seifert