Initializing an array of zeroes
It is well known that missing initializers for an array of scalars are defaulted to zero.
int A[5]; // Entries remain uninitialized
int B[5]= { 0 }; // All entries set to zero
But is this (below) guaranteed ?
int C[5]= { }; // All entries set to zero
The empty braced initialisation performs aggregation-initialization of the array: this leads to zero-initialization of the int
elements.
Yes, this is guaranteed.
Yes, according to the rule of aggregate initialization, it's guaranteed (that all elements of array C
will be value-initialized, i.e. zero-initialized to 0
in this case).
(emphasis mine)
If the number of initializer clauses is less than the number of members
and bases (since C++17)
or initializer list is completely empty, the remaining membersand bases (since C++17)
are initializedby their default initializers, if provided in the class definition, and otherwise (since C++14)
by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates).
PS:
int A[5]; // Entries remain uninitialized
"remain uninitialized" might not be accurate. For int A[5];
, all elements of A
will be default-initialized. If A
is static or thread-local object, the elements will be zero-initialized to 0
, otherwise nothing is done, they'll be indeterminate values.
In fact when you sayint A[5] = { 0 };
you are saying: Initialize the first element to zero. All the other positions are initialized to zero because of the aggregate inizialization.
This line is the real responsible for having your array full of zeroes: int A[5] = { };
That is why if you use int A[5] = { 1 };
you will only have the first position inizialized to 1.