Zero Array Initialization

It is well known that missing initializers for an array of scalars are zero by default.

int A[5]; // Entries remain uninitialized int B[5]= { 0 }; // All entries set to zero 

But is this guaranteed (below)?

 int C[5]= { }; // All entries set to zero 
+46
c ++ arrays initialization language-lawyer
Aug 11 '16 at 9:30
source share
3 answers

An empty fixed initialization performs array aggregation-initialization: this leads to zero initialization of int elements.

Yes, it is guaranteed.

+61
Aug 11 '16 at 9:34
source share

Yes, according to the aggregate initialization rule, he guaranteed (that all elements of the array C will be value-initialized , i.e. with zero initialization to 0 in this case).

(my accent)

If the number of initializer sentences is less than the number of and bases (since C++17) elements and bases (since C++17) or the list of initializers is completely empty , the remaining members and bases (since C++17) initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) empty lists in accordance with the usual rules for initializing a list (which performs the initialization of values ​​for types of nonclasses and non-aggregate classes with default constructors and aggregate initialization for aggregates).




PS:

 int A[5]; // Entries remain uninitialized 

"remain uninitialized" may be inaccurate. For int A[5]; all elements of A will be initialized by default . If A is a static or thread-local object, the elements will be initialized to 0 , otherwise nothing will be done, ll will be undefined values.

+33
Aug 11 '16 at 9:34
source share

In fact, when you say int A[5] = { 0 }; you say: Initialize the first element to zero. All other positions are initialized to zero due to aggregation initialization.

This line is the real responsibility that your array is filled with zeros: int A[5] = { };

That is why if you use int A[5] = { 1 }; , you will only have the first position initialized to 1.

+1
Aug 17 '16 at 7:45
source share



All Articles