Reputation: 1028
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.
Upvotes: 10
Views: 7124
Reputation: 158489
Objects with static storage duration are zero initialized. This is covered in the draft C++ standard section 3.6.2
Initialization of non-local variables which says:
Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.
and zero initialization is covered in 8.5
Initializers which says:
To zero-initialize an object or reference of type T means:
- if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T;103
- if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;
- if T is a (possibly cv-qualified) union type, the object’s first non-static named data member is zeroinitialized and padding is initialized to zero bits;
- if T is an array type, each element is zero-initialized;
- if T is a reference type, no initialization is performed.
Both bool and pointers are scalar types and therefore by the first bullet will be set to 0
.
Upvotes: 7
Reputation: 119219
§8.5/5 of the standard explains what it means to zero-initialize an object. For scalar types, the value after zero-initialization will be the result of converting 0
to the destination type.
The result of zero-initializing bool
is false
, since that is the result of converting 0
to bool
. Incidentally, bool
is an integer type.
The result of zero-initializing a pointer is a null pointer value, since that is the result of converting 0
to a pointer type.
Upvotes: 8
Reputation: 409196
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
Upvotes: 22