Avoiding "variable might not have been initialized"

Posted by Mason Wheeler on Stack Overflow See other posts from Stack Overflow or by Mason Wheeler
Published on 2010-04-26T22:29:42Z Indexed on 2010/04/26 22:33 UTC
Read the original article Hit count: 269

I recently ran across a routine that looks something like this:

procedure TMyForm.DoSomething(list: TList<TMyObject>; const flag: boolean);
var
  local: integer;
begin
  if flag then
    //do something
  else local := ExpensiveFunctionCallThatCalculatesSomething;

  //do something else
  for i := 0 to list.Count do
    if flag then
      //do something
    else if list[i].IntValue > local then //WARNING HERE
        //do something else
end;

This gives Variable 'local' might not have been initialized even though you can tell by reading the code that you won't hit that line unless the code branch that initializes it has run.

Now, I could get rid of this warning by adding a useless local := 0; at the top of the procedure, but I wonder if there might not be a better way to structure this to avoid the issue. Anyone have any ideas?

© Stack Overflow or respective owner

Related posts about delphi

Related posts about compiler-warnings