https://en.cppreference.com/w/cpp/language/zero_initialization shows that zero-initialization happens in the following scenario:
int array[32] = {};
; but never says anything about this:
int array[32] = { 0 };
Does the latter also zero-initialize the whole array in c++, or only the first element? If so, is it also true for structs?
ISO/IEC N489 §9.4.1 states
(5) For a non-union aggregate, each element that is not an explicitly initialized element is initialized as follows:
(5.1) If the element has a default member initializer (11.4), the element is initialized from that initializer.
(5.2) Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list (9.4.4).
(5.3) Otherwise, the program is ill-formed.
§9.4.4 states
- (3.11) Otherwise, if the initializer list has no elements, the object is value-initialized.
Value-initialization of a scalar leads to its zero-initialization. Thus, the second one explicitly initializes with 0 only array[0]
and the rest of the elements will be zero-initialized.
Thus, the following code
int array[4] = {13};
initializes array
with values
{13, 0, 0, 0}
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