Why does the compiler warn that the variable cannot be initialized?

I get a compiler warning that I don't understand:

procedure Test; var Var1: Integer; begin while True do begin try if System.Random > 0.5 then begin ShowMessage('Skipping'); continue; // If I remove this line, the warning goes away end; Var1:=6; except on E:Exception do begin ShowMessage('Error'); raise; end; end; ShowMessage(IntToStr(Var1)); // Compiler warning on this line end; end; 

When I compile this in Delphi 2010, I get:

[DCC Warning] OnlineClaimManagerMainU.pas (554): W1036 Variable 'Var1' may not have been initialized

If I delete the call to continue, the warning disappears.

Also, if I delete the try / except clause (and leave a continuation), the warning disappears.

How will this line execute without initializing Var1?

+4
source share
3 answers

Var1 will always be initialized before using it. The compiler gets confused by try - except processing: your code is too complex for the compiler to actually determine that Var1 always initialized. He sees that there can be a handled exception before Var1:=6; which would leave Var1 uninitialized, but does not see that this exception will always be raised again.

+4
source

You should, but ShowMessage(IntToStr(Var1)); into the try block, except for the block. Then it should be clear to the compiler that Var1 is initialized and looks more like clean code.

0
source

This is a very good warning. What it says is that you are not assigning any value to a variable that can be used somewhere else in your code. The warning also reports that if it is used, then the value assigned to it may not be what you expect.

0
source

All Articles