Delphi布尔变量值

Shi*_*h11 2 delphi boolean initialization

为什么在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.
Run Code Online (Sandbox Code Playgroud)

这会将结果显示为

哪里 true is label1 and false is label2

Avo*_*ägi 19

实际上没有初始化局部变量,但是全局变量和对象字段被初始化为零(对于布尔变量,这意味着'false').

因此,您必须自己初始化局部变量,如果不这样做,编译器甚至会生成警告.

您还应该查看有关变量的Delphi文档.

  • @ Shirish11:不,这就是在这种情况下恰好发生的事情.将代码移到其他地方,将代码添加到项目中,它可能会发生变化.**不要**依赖它.未初始化意味着除非您自己初始化,否则您根本无法预测其值. (6认同)
  • 它恰好是真的比false(= 0)更多的可能值.因此,对于未初始化的布尔值,您更有可能遇到true作为false. (3认同)
  • @Marco,我的陈述,即TRUE更可能是未初始化的变量只是一个统计观察.这意味着为什么Shirish11将TRUE视为局部变量的"默认".这可能是特定于Delphi编译器的,但这正是这个问题所要求的. (2认同)