Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ c-style zero-initialization { 0 }

Tags:

c++

arrays

c

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?


1 Answers

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}
like image 188
eanmos Avatar answered Sep 20 '25 14:09

eanmos