为什么编译器警告该变量可能未被初始化

为什么编译器警告该变量可能未被初始化

本文介绍了为什么编译器警告该变量可能未被初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个编译器警告我不明白:

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;

当我在Delphi 2010中编译时,我得到:

When I compile this in Delphi 2010 I get:

如果我删除继续的呼叫,则警告消失。

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

此外,如果我删除try / except子句并保持继续),警告消失。

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

如果没有Var1被初始化,那么执行方式如何处理?

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

推荐答案

Var1 将始终在使用前进行初始化。编译器被 try - 处理困惑:你的代码太复杂,编译器能够真正确定始终初始化 Var1 。它看到在 Var1:= 6; 之前可能会有一个处理的异常,这将使 Var1 未初始化,但它没有不会看到该例外将永远被重新提出。

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.

这篇关于为什么编译器警告该变量可能未被初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:55