Reputation: 3871
Code like this can work fine:
char str[] = {'a', 'b', '\0'};
The left is an auto variable(array).
Code like this can NOT work:
char *str = {'a', 'b', '\0'};
The left side is a pointer. The pointer points to an unknown space, so this will fail.
My question is, what is the type of the right side?
In C++ 11, an initialize list becomes std::initializer_list
. But what about old C++ 03?
Upvotes: 8
Views: 303
Reputation: 206536
In C++03 the right side is an initializer-list. It does not have any type, it just serves the purpose of providing a means to initialize values for identifiers.
This is defined in:
C++03 8.5.1 Initializers [dcl.init]
A declarator can specify an initial value for the identifier being declared. The identifier designates an object or reference being initialized. The process of initialization described in the remainder of 8.5 applies also to initializations specified by other syntactic contexts, such as the initialization of function parameters with argument expressions (5.2.2) or the initialization of return values (6.6.3).
initializer:
= initializer-clause
( expression-list )
initializer-clause:
assignment-expression
{ initializer-list ,opt }
{ }
initializer-list:
initializer-clause
initializer-list , initializer-clause
Upvotes: 4
Reputation: 340218
In C++03 a brace-enclosed initializer is just a syntactic device that can be used to initialize aggregates (such as arrays or certain types of classes or structs). It does not have a 'type' and can only be used for those specific kinds of initializers.
8.5.1/2 "Aggregates":
When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace- enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order.
Upvotes: 8
Reputation: 111130
From the draft of C++11:
8.5 Initializers
16 The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. The source type is not defined when the initializer is a braced-init-list or when it is a parenthesized list of expressions.
Upvotes: 0