2
votes

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.)

1
What is STRUCT? - juanchopanza
@juanchopanza: a C-struct of any kind - Samantha
there is no such thing as idiomatic form.. = { 0 } was the only form of initialization allowed in C, C++11 allows empty braced list and uniform initialization struct s {}; Note that there are underwater reefs with its use, uniform initialization may do not what you expect with non-trivial classes that accept initializer_list. E.g. vector<int> v {3}; creates vector containing one element with value of 3. - Swift - Friday Pie
Also, the meaning of { 0 } is subtly different to your understanding. Under the old "C" rules, this initialises the first members to the values given, then zeros any other members. I.e. { 1 } does not set all members to 1. - Gem Taylor

1 Answers

2
votes

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 ]