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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With