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?
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.
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.
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.
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.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With