Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

delphi - Why is the Compiler warning that variable may not be initialized?

I am getting a compiler warning 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' might not have been initialized

If I remove the call to 'continue', the warning goes away.

Also, if I remove the try/except clause (and leave the continue), the warning goes away.

How will execution get to the line in question without Var1 being initialised?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Var1 will always be initialised before it is used. The compiler gets confused by try-except handling: your code is too complex for the compiler to be able to actually determine that Var1 is always initialised. It sees there may be a handled exception before Var1:=6;, which would leave Var1 uninitialised, but it doesn't see that that exception will always be re-raised.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...