I believe that all numerical variables are initialized to zero, but what about things like static bool
or static MyClass*
?
I have looked around the interwebs, but most results I found are for how to initialize things like ints to non-zero values, and I just want to know the defaults.
The default initialization value of a static variable is zero, even if it is not assigned, which is not the case in a local variable. It is mandatory to initialize the static variable using the static keyword in C else it will return an error.
A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence. A static object of class type will use the default constructor if you do not initialize it.
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.
3) Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage.
Global variables, local static variables, and static member variables are all zero initialized, unless otherwise initialized. This means floating point values are zero, booleans are false, pointers are nullptr etc
See http://en.cppreference.com/w/cpp/language/zero_initialization
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