I was wondering what the cpp standard says about global initialization. I have found this answer helpful, but there was no mention of a pointer type.
Is there a guarantee that this will work?
char* myptr
int main()
{
if (myptr == NULL)
{
std::cout << "All good!" << std::endl;
}
}
Yes, a pointer defined at namespace scope (global namespace in your case) is guaranteed to be initialized to the correct null pointer value of the type.
For the standard references,
3.6.2[basic.start.init]/2
"Variables with static storage duration ... shall be zero-initialized (8.5)"
8.5[dcl.init]/6
"To zero-initialize ... means: if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;[106]"106) As specified in 4.10, converting an integer literal whose value is 0 to a pointer type results in a null pointer value.
(emphasis mine)
I would append to the previous post of @Cubbi that according to the same Standard the scalar type is
Arithmetic types (3.9.1), enumeration types, pointer types, pointer to member types (3.9.2), std::nullptr_- t, and cv-qualified versions of these types (3.9.3) are collectively called scalar types
And then
Non-local variables with static storage duration are initialized as a consequence of program initiation.
and
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.
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