9

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.

6
  • It's legit in C. Array members are initialized from the beginning. So you even can: int i[] = { [1] = func(i[0]), [0] = 5 }; Commented Aug 13, 2018 at 9:09
  • Found some tips on this forum.. in this case a reference to the array itself is not needed, you could also initialize the whole array using a single value 42, see stackoverflow.com/questions/629017/… Commented Aug 13, 2018 at 9:14
  • @Goodies you could also initialize the whole array using a single value 42 Would you mind to show how? Commented Aug 13, 2018 at 10:09
  • Read the topic I linked. This is valid C++ syntax: char array[100] = {42}; (note you will have to specify the array length in the declaration..) Commented Aug 14, 2018 at 14:17
  • @Goodies in this case all the rest elements will be zeroes. Commented Aug 14, 2018 at 14:21

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.