Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi boolean variable values

Why is that in Delphi Boolean variable initialized in global scope is false and variable initialized in local scope is true?

Can we change any of the default values so that both (global and local variables) have the same values on initialization?

sample code

    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.

This displays me the result as

where true is label1 and false is label2

like image 650
Shirish11 Avatar asked Mar 23 '26 08:03

Shirish11


2 Answers

Local variables are actually not initialized, but global variables and object fields are initialized to zero (which means 'false' for boolean variables).

Therefore you always have to initialize local variables yourself, compiler even generates a warning if you don't.

You should also check out Delphi documentation on variables.

like image 82
Avo Muromägi Avatar answered Mar 24 '26 21:03

Avo Muromägi


Global variables are always initialized to zero - in boolean that means false. Local variables in procedures and methods are not initialized at all. You need to assign value to them yourself.

like image 36
evilone Avatar answered Mar 24 '26 21:03

evilone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!