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.

αλεχολυτ
  • 4,792
  • 1
  • 35
  • 71
  • It's legit in C. Array members are initialized from the beginning. So you even can: `int i[] = { [1] = func(i[0]), [0] = 5 };` – KamilCuk Aug 13 '18 at 09: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 https://stackoverflow.com/questions/629017/how-does-array100-0-set-the-entire-array-to-0 – Goodies Aug 13 '18 at 09:14
  • @Goodies `you could also initialize the whole array using a single value 42` Would you mind to show how? – Killzone Kid Aug 13 '18 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..) – Goodies Aug 14 '18 at 14:17
  • @Goodies in this case all the rest elements will be zeroes. – αλεχολυτ Aug 14 '18 at 14:21
  • Ah I've tested it, you're right.. I've only looked at the opening. – Goodies Aug 15 '18 at 14:17

1 Answers1

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

Community
  • 1
  • 1
YSC
  • 38,212
  • 9
  • 96
  • 149