cppguy
cppguy

Reputation: 3723

initializer lists in C and C++

For some reason I had this idea that C and C++ worked like this:

int foo[10] = {57};
for (int i=0; i<10; ++i)
    assert (foo[i] == 57);

Turns out the remaining ints are initialized to 0, not 57. Where did I get this idea? Was this true at one point? Was it ever true for structure initializer lists? When did arrays and structures neatly and correctly start initializing themselves to 0 values when assigned to = {} and = {0}? I always thought they'd initialize to garbage unless explicitly told otherwise.

Upvotes: 3

Views: 1749

Answers (2)

bames53
bames53

Reputation: 88235

Where did I get this idea?

It's apparently a relatively common misconception, as I've heard the same thing from a number of other people recently. Perhaps you picked it up from somebody else with this wrong idea, or perhaps the idea is just 'intuitive'.

{} Initialization has worked as it does at least as far back as C89. I'm not aware of it ever working differently, or any compilers that ever did it differently.

For initializer lists when initializing an aggregate type (like an array):

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 (8.5.4). — Aggregates [dcl.init.aggr] 8.5.1p7

In C++ terms, when you use an empty initializer the object is value-initialized.

To value-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.

— if T is an array type, then each element is value-initialized;

— otherwise, the object is zero-initialized.

                                                                                              — Initializers [dcl.init] 8.5p7

Upvotes: 2

cnicutar
cnicutar

Reputation: 182794

It's been this way forever, as long as initializers existed. C89 says:

If there are fewer initializers in a list than there are members of an aggregate, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Upvotes: 12

Related Questions