Reputation: 303
Is there a difference between initializing a structure these two ways:
structVar = {}
and
structVar = {0}
Upvotes: 0
Views: 188
Reputation: 56577
corrected
If the structure is an aggregate, the 2 definitions perform the same thing. From the C++11 standard (N3337):
8.5.1/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 its brace-or-equal-initializer or, if there is no brace-or-equal- initializer, from an empty initializer list (8.5.4).
If the structure contains two members, like
struct S
{
int x;
double y;
};
then structVar = {}
will value-initialize the members, i.e. they will become zero (or if the members are non-PODs, the default ctor will be called).
The line structVar = {0}
will initialize only the first member of the struct with zero. Since in this case you have an aggregate, the rest of the members are value-initialized by empty lists, so effectively you have
structVar = {0, {} };
C++14 added the possibility of aggregate initialization for aggregates containing brace-or-equal initialized members, i.e.
struct S
{
int x;
double y{1.1}; // or double y = 1.1;
}
In this case,
structVar = {0};
initializes x
with 0 and y
with 1.1. This was not possible before C++14.
PS: just tested the code above, clang++ compiles it with -std=c++1y
, however g++ 4.9.2 rejects it even if I compile with -std=c++14
.
Upvotes: 4
Reputation: 227548
It really depends on the nature of the struct.
If it is an aggregate, the two are largely equivalent. However, the first one is general in that it simply value-initializes the struct. The second one requires that the struct's first member be initializable with 0
, and initializes the rest of elements as if they were each initialized by an empty initializer {}
, in other words,
structVar = {0, {}, {}, {}, ..... };
so each remaining element is value-initialized.
If it is not an aggregate, then it depends on what constructors, if any, have been provided. There simply isn't enough information to say.
Upvotes: 5