Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding "variable might not have been initialized"

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?

like image 886
Mason Wheeler Avatar asked Apr 26 '10 22:04

Mason Wheeler


People also ask

Why does it say variable might not have been initialized?

If the compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.

What happens if you don't initialize a variable?

An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.

What happens if I forget to declare a variable and initialize a variable?

If we do not initialize the variable, then it will take in the garbage value. In Primary Type, we use built-in data types such as int, float, char, boolean, double, long etc. and in User Defined Type, we use user-defined data types such as struct, Union, enum, typedef etc.


2 Answers

I would separate it into two for-loops--one for when flag is true and one for when flag is false. As an added benefit, you won't have to execute the if-statement on every iteration.

like image 88
Neil Avatar answered Oct 06 '22 01:10

Neil


IMO, the assignment to 0 isn't useless here - it's beneficial to maintanability. So you'll save someone (perhaps your future self) from having to spend a minute or two to determine that the code works. And the design cleverness will likely be lost on them (even if it's you!)

like image 24
Chris Thornton Avatar answered Oct 05 '22 23:10

Chris Thornton