8

Usually when we initialize an array, we would probably do:

int arr[] = {1, 2, 3, 4, 5};

But is it ok to explicitly limit the length of the array as below? :

int arr[3] = {1, 2, 3, 4, 5};

Despite some warnings from the compiler, the executable doesn't seem to have any problems.

Pacerier
  • 86,231
  • 106
  • 366
  • 634

1 Answers1

10

No, it's not OK. From C99, 6.7.8.2:

Constraints

  1. No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

In my read, this means that providing excess initializer elements is a constraint violation, so it invokes undefined behavior.

  • To clarify do you mean that in the example above arr[5] and above is defined behavior but arr[4] and below is undefined? – Pacerier Sep 21 '13 at 05:44
  • 1
    @Pacerier If I understand the Standard correctly, then yes, exactly. –  Sep 21 '13 at 05:45