I know that, in Delphi, instance variables and global variables are initialized to zero (this has been asked here before).
However, what about static variables (class var
)? I would expect class vars to be initialized to zero, just like global variables. But I've seen too many new Delphi compiler features that were still half-baked to assume that it works, without documentation that actually states a guarantee.
The Help has no index entry for "class var". The "Fields" topic mentions class fields, but does not specify whether they're initialized at program startup. And the obvious fix, of explicitly initializing them (class var X: Integer = 0;
), doesn't compile ("';' expected but '=' found").
Are class variables initialized to zero? Is there documentation that explicitly states this?
3) Static variables (like global variables) are initialized as 0 if not initialized explicitly.
In C++, class variables are initialized in the same order as they appear in the class declaration.
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.
Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is given a memory address to use to store data, the default value of that variable is whatever (garbage) value happens to already be in that memory address!
I'm not aware of any documentation that explicitly states it, but class vars are just a special type of global variable, and globals get zeroed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With