Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

local variable initialized in delphi?

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?

Example:

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Consider this program:

{$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

Now consider this program:

{$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.

This time the output is:

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.

Or try this program:

{$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.

Now the output is:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...