Reputation: 1617
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
Upvotes: 3
Views: 12711
Reputation: 1593
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.
Upvotes: 22
Reputation: 22740
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.
Upvotes: 2