爲什麼在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
你是對的它給出了警告,但它的值默認爲'true' – Shirish11
@ Shirish11:不,這正是在這種情況下發生的情況。將代碼移動到其他位置,將代碼添加到項目中,並且可能會更改。 **不要**依靠它。未初始化意味着除非您自己初始化,否則根本無法預測該值。 –
@MarjanVenema是,當你有局部變量時,它不會被初始化爲零(在這種情況下爲false),並且有一些垃圾值被賦值給它,因此'非零(true)' – Shirish11