Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a global pointer initialized to zero?

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;
    }
}
like image 928
Bartlomiej Lewandowski Avatar asked Dec 26 '13 17:12

Bartlomiej Lewandowski


2 Answers

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)

like image 170
Cubbi Avatar answered Sep 17 '22 22:09

Cubbi


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.

like image 41
Vlad from Moscow Avatar answered Sep 19 '22 22:09

Vlad from Moscow