Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the type of initialize list in C++ array?

Tags:

c++

c

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?

like image 568
liuyanghejerry Avatar asked May 16 '12 08:05

liuyanghejerry


2 Answers

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.

like image 53
Michael Burr Avatar answered Oct 15 '22 00:10

Michael Burr


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
like image 38
Alok Save Avatar answered Oct 15 '22 02:10

Alok Save