How to initialize this variable?

I have the following

char mem_pool[1024*1024*64]; int main() { // ... } 

I am trying to get a complete understanding of how mem_pool will be initialized. After many searches, my findings are:

  • this is static initialization (not like in the static keyword, but as in "run before program execution - during the static initialization phase")
  • it will work in 2 stages: initialization of zero and initialization by default (the second phase will do nothing)
  • it is a POD array, therefore, the default initialization for each element should be applied, but due to the previous two points we will not have an array of undetectable values ​​(as we would with char ar[N] in the function area), but an array of zeros.

Can someone help me expose what is guaranteed by the language and correct me if I am wrong?

I also thought about doing any of the following

 char mem_pool[1024*1024*64] {}; char mem_pool[1024*1024*64] = ""; 

I suspect this is the best / recommended practice, but now I need to understand my initial question.

+6
source share
1 answer

Your understanding is correct.

All elements of the array will be initialized with zeros, since the array has a static storage duration:

[C++11: 3.6.2/2]: Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) must be initialized with zeros (8.5) before any other initialization. [..]

[C++11: 8.5/5]: For zero initialization of an object or reference of type T means:

  • if T is a scalar type (3.9), the object is set to 0 (zero), taken as an integral constant expression converted to T ;
  • If T is a (possibly cv-qualified) non-unit class, each non-static data element and each subobject of the base class is initialized to zeros, and padding is initialized to zero bits;
  • If T is a (possibly cv-qualified) join type, the objects of the first non-static named data element are initialized with zeros and padding is initialized with zero bits;
  • if T is an array type, each element is initialized to zero;
  • if T is a reference type, initialization is not performed.

If it did not have a static storage duration, all elements would have undefined values:

[C++11: 8.5/11]: If no initializer is specified for an object, the object is initialized by default ; if initialization fails, an object with automatic or dynamic storage duration has an undefined value. [..]

[C++11: 8.5/6]: For initialization by default, an object of type T means:

  • If T is (possibly cv-qualit) a class type (section 9), the default constructor for T is called (and initialization is poorly formed if T does not have an available default constructor);
  • if T is an array type, each element is initialized by default;
  • otherwise, initialization fails .
+5
source

Source: https://habr.com/ru/post/983933/


All Articles