2011-11-18 168 views
1

爲什麼在Delphi布爾變量在global scope is false初始化和變量初始化在local scope is true德爾福布爾變量值

我們可以更改任何默認值,以便both (global and local variables)在初始化時具有相同的值嗎?

示例代碼

unit Unit1; 

    interface 

    uses 
     Windows, Messages, SysUtils, Variants, Classes, Graphics, 
     Controls, Forms,Dialogs, StdCtrls; 

    type 
     TForm1 = class(TForm) 
     Button1: TButton; 
     Label1: TLabel; 
     Label2: TLabel; 
     procedure Button1Click(Sender: TObject); 
     private 
     { Private declarations } 
     public 
     { Public declarations } 
     end; 

    var 
     Form1: TForm1; 
     bool1:boolean; 

    implementation 

    {$R *.dfm} 

    procedure TForm1.Button1Click(Sender: TObject); 
    var 
    bool :boolean; 
    begin 
    if bool then 
     label1.Caption:='true' 
    else 
     label1.caption:='false'; 
    if bool1 then 
     label2.Caption:='true' 
    else 
     label2.caption:='false'; 

    end; 

    end. 

這顯示了我的結果作爲

其中true is label1 and false is label2

回答

18

局部變量實際上沒有初始化,但全局變量和對象字段被初始化爲零(對於布爾變量,這意味着'假')。

因此,您必須始終自己初始化局部變量,否則編譯器甚至會在您不需要時生成警告。

您還應該查看變量上的Delphi documentation

+0

你是對的它給出了警告,但它的值默認爲'true' – Shirish11

+5

@ Shirish11:不,這正是在這種情況下發生的情況。將代碼移動到其他位置,將代碼添加到項目中,並且可能會更改。 **不要**依靠它。未初始化意味着除非您自己初始化,否則根本無法預測該值。 –

+1

@MarjanVenema是,當你有局部變量時,它不會被初始化爲零(在這種情況下爲false),並且有一些垃圾值被賦值給它,因此'非零(true)' – Shirish11

2

全局變量始終初始化爲零 - 在布爾值中表示爲false。程序和方法中的局部變量根本不會被初始化。你需要爲他們自己分配價值。