As static variable declaration without any value assigned goes in BSS section of code. where it will be automatically initialed to zero.
Question: suppose, if declare static pointer without any assignment, then whether should it have zero value for address or value?
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.
Static pointers in C/ C++ These variables holds their value even after they are out of their scope. Once declared and initialized they are not re-declared i.e., once the memory is allocated, then they exist till the termination of that program. A static pointer declaration as shown below.
But in some cases it generates code that uses two guard variables and initialize each static variable separately. The problem is when such two types of initialization are mixed in executable binary. In such case it may happen that second static variable will get initialized twice.
Without an initializer, the values of static and extern pointers are automatically initialized to null pointers (pointers to memory location 0).
In C a static pointer will be initialized to null, the draft C99 standard section 6.7.8
Initialization paragraph 10 says:
an object that has static storage duration is not initialized explicitly, then:
and included the following bullet:
— if it has pointer type, it is initialized to a null pointer;
So no storage is allocated for it, it is a null pointer. Also note it is an implementation defined behavior where static variables are stored.
The relevant section for the C++ draft standard would be section 8.5
Initializers paragraph 13 which says (emphasis mine):
If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value. [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. —end note ]
zero-initialize is covered in paragraph 6 which says:
To zero-initialize an object or reference of type T means:
and has the following bullet:
— 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
where footnote 103
says (emphasis mine):
As specified in 4.10, converting an integral constant expression whose value is 0 to a pointer type results in a null pointer value.
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