Search code examples
delphidelphi-xe7

Default initial value of a variable in Delphi?


Developing a window-32 bit application by using DelphiXE-7. I’ve following piece of code-

Procedure TMainForm.Button1Click(Sender: TObject);
Var
  iNum: Integer;
  bExit: Boolean;
Begin
  ShowMessage(IntToStr(iNum));
  repeat
    Inc(iNum);
    bExit := True;
  until Exit;
End;

I know that not initializing iNum before using it may cause this problem, but then it should also come at debugging time.

But when I’m debugging or running compiled exe MessageBox is showing as “0” which seems correct, but when we are installing build and running the same procedure then MessageBox is showing some garbage value instead of zero. Something like “1632824”.

Only difference between compiling and Build generation is that later one is not creating dcu.

Please Advise Accordingly.


Solution

  • Global variables are in the application data segment, they are initialized with zeros when the program starts.

    Class fields are initialized with zeros when objects are created (they might be filled later in constructors, Loaded(), etc).

    Variables

    Memory for local variables, like your iNum, is allocated dynamically in the program stack just during the function call, and local variable values are random and unpredictable when uninitialized. That is why initialization is a necessary step.

    The exception to this rule is compiler-managed types - strings, interfaces, variants, dynamic arrays, etc - they are initialized with empty values.

    Initializing Strings