德尔福布尔变量值
问题描述:
为什么在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
答
局部变量实际上没有初始化,但全局变量和对象字段被初始化为零(对于布尔变量,这意味着'假')。
因此,您必须始终自己初始化局部变量,否则编译器甚至会在您不需要时生成警告。
您还应该查看变量上的Delphi documentation。
答
全局变量始终初始化为零 - 在布尔值中表示为false。程序和方法中的局部变量根本不会被初始化。你需要为他们自己分配价值。
你是对的它给出了警告,但它的值默认为'true' – Shirish11
@ Shirish11:不,这正是在这种情况下发生的情况。将代码移动到其他位置,将代码添加到项目中,并且可能会更改。 **不要**依靠它。未初始化意味着除非您自己初始化,否则根本无法预测该值。 –
@MarjanVenema是,当你有局部变量时,它不会被初始化为零(在这种情况下为false),并且有一些垃圾值被赋值给它,因此'非零(true)' – Shirish11