局部变量在德尔福初始化? [英] local variable initialized in delphi?

查看:88
本文介绍了局部变量在德尔福初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在较旧的程序代码的审阅过程中,出现以下问题:在开始后立即初始化方法中的所有局部变量。通常,局部变量不会被初始化。但是我们有一个将所有变量都初始化为0的过程。有人知道怎么发生吗?

During a review process of an older programm code the following question arised: All local variables in a method are initialized right after begin. Usually local variables are not initialized. But we have a procedure where all variables are initialized to 0. Does anybody has an idea how this could happen?

示例:

type
  TPrices = array[0..10, 0..5] of Integer;

procedure DoSomething();
var
  mPrices : TPrices;
  mValue  : Integer; 
begin
  if (mPrices[0,0] = 0) then
    MessageDlg('Zero', mtInformation, [mbOK], 0);
  if (mValue = 0) then
    MessageDlg('Zero Integer', mtInformation, [mbOK], 0);
end;


推荐答案

这只是偶然。变量未初始化。该变量将驻留在堆栈上,如果碰巧最后一次写入堆栈该位置的值是零,则该值仍将为零。

This is just down to chance. The variable is not initialized. The variable will reside on the stack, and if it so happens that whatever was last written to that location of the stack was zero, then the value there will still be zero.

未托管类型的局部变量未初始化。

Local variables of unmanaged types are not initialized. Do not allow coincidences like the above persuade you otherwise.

请考虑以下程序:

{$APPTYPE CONSOLE}

type
  TPrices = array[0..10, 0..5] of Integer;

procedure Foo;
var
  mPrices: TPrices;
begin
  Writeln(mPrices[0,0]);
end;

begin
  Foo;
end.

在计算机上运行时,输出为:

When I run on my machine, the output is:


1638012

现在考虑该程序:

{$APPTYPE CONSOLE}

type
  TPrices = array[0..10, 0..5] of Integer;

procedure Foo;
var
  mPrices: TPrices;
begin
  Writeln(mPrices[0,0]);
  FillChar(mPrices, SizeOf(mPrices), 0);
end;

procedure Bar;
var
  mPrices: TPrices;
begin
  Writeln(mPrices[0,0]);
end;

begin
  Foo;
  Bar;
end.

这次输出为:


1638012
0

碰巧这两个函数将其局部变量放在同一位置并且第一个函数在返回之前将局部变量归零的事实会影响第二个函数中另一个局部变量的未初始化值。

It so happens that the two functions place their local variables in the same location and the fact that the first function call zeroed the local variable before returning affects the uninitialized value of the other local variable in the second function.

或者尝试以下程序:

{$APPTYPE CONSOLE}

type
  TPrices = array[0..10, 0..5] of Integer;

procedure Foo;
var
  mPrices: TPrices;
begin
  Writeln(mPrices[0,0]);
  FillChar(mPrices, SizeOf(mPrices), 0);
  mPrices[0,0] := 666;
end;

procedure Bar;
var
  mPrices: TPrices;
begin
  Writeln(mPrices[0,0]);
  Writeln(mPrices[0,1]);
end;

begin
  Foo;
  Bar;
end.

现在输出为:


1638012
666
0

您可能会想到,许多不同的事情可能导致该堆栈空间的内容在变化。因此,请相信您所知道的。非托管类型的局部变量未初始化。

As you might imagine, many different things could lead to the content of that stack space changing. So trust what you know. Local variables of unmanaged types are not initialized.

这篇关于局部变量在德尔福初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆