Are delphi variables initialized with a value by default?
Solution 1:
Yes, this is the documented behaviour:
Object fields are always initialized to 0, 0.0, '', False, nil or whatever applies.
Global variables are always initialized to 0 etc as well;
Local reference-counted* variables are always initialized to nil or '';
Local non reference-counted* variables are uninitialized so you have to assign a value before you can use them.
I remember that Barry Kelly somewhere wrote a definition for "reference-counted", but cannot find it any more, so this should do in the meantime:
reference-counted == that are reference-counted themselves, or directly or indirectly contain fields (for records) or elements (for arrays) that are reference-counted like:
string, variant, interface
or dynamic array or static array containing such types.
Notes:
-
record
itself is not enough to become reference-counted - I have not tried this with generics yet
Solution 2:
Global variables that don't have an explicit initializer are allocated in the BSS section in the executable. They don't actually take up any space in the EXE; the BSS section is a special section that the OS allocates and clears to zero. On other operating systems, there are similar mechanisms.
You can depend on global variables being zero-initialized.
Solution 3:
Class fields are default zero. This is documented so you can rely on it. Local stack varaiables are undefined unless string or interface, these are set to zero.