Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed to initialize array recursively? [duplicate]

I have the following code snippet:

int i[] = {42, i[0]};

Is such initialization allowed or leads to undefined behaviour?

Three major compilers (gcc, clang, msvc) give me 42 for i[1]. Hence looks legit, but I would like to see a cite from the standard for this case.

like image 733
αλεχολυτ Avatar asked Feb 04 '23 22:02

αλεχολυτ


1 Answers

Yes, it is well-defined.

int i[] = {42, i[0]};

This is an aggregate1 initialization2. Aggregate initialization observes this rule:

[dcl.init.aggr]/6

The initializations of the elements of the aggregate are evaluated in the element order. That is, all value computations and side effects associated with a given element are sequenced before those of any element that follows it in order.


1)http://eel.is/c++draft/dcl.init.aggr#1

2)http://eel.is/c++draft/dcl.init.aggr#3

like image 60
YSC Avatar answered Feb 06 '23 10:02

YSC