Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a (C/C++) array initialization reference itself?

Tags:

c++

I was wondering about an initialization of the following form:

int  array[] = { v - 1, array[0] + 1 } ; 

In the initialization of the second element, the value of the first is used, but the entire array is not yet initialized. This happens to compile with g++, but I was unsure whether this is actually portable and a well defined construct?

like image 584
Peeter Joot Avatar asked Feb 27 '12 15:02

Peeter Joot


People also ask

Are arrays in C automatically initialized?

The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros.

What happens when an array is initialized in C?

The remaining array elements will be automatically initialized to zero. If an array is to be completely initialized, the dimension of the array is not required. The compiler will automatically size the array to fit the initialized data.

What happens when an array is initialized?

Initialization of multidimensional arrays Listing the values of all elements you want to initialize, in the order that the compiler assigns the values. The compiler assigns values by increasing the subscript of the last dimension fastest.


1 Answers

See 3.3.2 Point of declaration:

The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:

int x = 12; { int x = x; } 

Here the second x is initialized with its own (indeterminate) value. —end example ]

So you are referring to the array correctly, its name is known after the =.

Then, 8.5.1 Aggregates:

An aggregate is an array or a class [...]

17: The full-expressions in an initializer-clause are evaluated in the order in which they appear.

However, I see no reference to when the evaluated values are actually written into the array, so I wouldn't rely on this and would even go so far to declare your code as not well defined.

like image 194
Sebastian Mach Avatar answered Sep 28 '22 22:09

Sebastian Mach