Search code examples
cc89

Initialize an Array Literal Without a Size


I'm curious about the following expression:

int ints[] = { 1, 2, 3 };

This seems to compile fine even in c89 land with clang. Is there documentation about this? I can't seem to figure out the correct terminology to use when searching for it (and I'd rather not go through and read the entire c89 spec again).

Is this an extension? Is the compiler simply inferring the size of the array?

EDIT: I just remembered you guys like chunks of code that actually compile so here it is:

/* clang tst.c -o tst -Wall -Wextra -Werror -std=c89 */
int main(int argc, const char *argv[]) {
  int ints[] = { 1, 2, 3 }; 
  (void)(ints); (void)(argc); (void)(argv);
  return 0; 
}

Solution

  • It's part of standard C since C89:

    §3.5.7 Initialization

    If an array of unknown size is initialized, its size is determined by the number of initializers provided for its members. At the end of its initializer list, the array no longer has incomplete type.

    In fact, there is an almost exact example:

    Example:

    The declaration

    int x[] = { 1, 3, 5 };
    

    defines and initializes x as a one-dimensional array object that has three members, as no size was specified and there are three initializers.