Search code examples
c++c++11uniform-initialization

C++ uniform initialization in C arrays and structs


I've seen some old code that looks like this: char foo[100] = { 0 };. Something similar happens with structs, like so: STRUCT st = { 0 };. The intention in both cases is clear, namely to zero-initialize the respective variables. As such, char foo[100] {}; and STRUCT st {}; would have been more idiomatic.

My question is: should the code with <variable> = { 0 } be expected to achieve the same outcome? I've tested this with release-build binaries and the elements appear to be zero-initialized, but is this guaranteed by the standard? It seems to me that <variable> = { 0 } should only guarantee for the first element of the variable (array element or struct member) to be zero.

Also, what behavior is indicated by the similar declarations char foo[100] = {}; and STRUCT st = {}?

(Motivation behind this question is that I'd change all the declarations to the idiomatic form, but if there is no guarantee of zero-initialization then the issue is something more serious and worth opening a ticket over.)


Solution

  • It seems to me that <variable> = { 0 } should only guarantee for the first element of the variable (array element or struct member) to be zero.

    That syntax, for POD types, is the same as <variable> = {};

    Anything that is not explicitly specified is initialized to zero. Use of <variable> = { somve_value } makes a difference only when some_value is other than zero.

    Even though the same syntax can be used for non-POD types, the elements that are of non-POD type that are not explicitly initialized are initialized using their default constructors.

    From 8.5.1 Aggregates/7:

    If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from an empty initializer list ([dcl.init.list]). [ Example:

    struct S { int a; const char* b; int c; };
    S ss = { 1, "asdf" };
    

    initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. — end example ]