Search code examples
carraysclangsizeofc89

Using sizeof() in array declarations in C89


I was under the impression that variable-size array declarations were not possible in C89. But, when compiling with clang -ansi I am able to run the following code:

double array[] = { 0.0, 1.0, 2.0, 3.0, 4.0 };
double other_array[sizeof(array)] = { 0.0 };

What is going on here? Is that not considered a variable-size array declaration?


Solution

  • That is because result of sizeof operator is constant expression, so it does not qualify for VLA, just like the following declaration:

    int other_array[5];
    

    cannot be variable length array either. From C11 (N1570) §6.6/p6 Constant expressions (emphasis mine going forward):

    An integer constant expression117) shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts.

    For sake of completeness, the sizeof operator does not always results into constant expression, though this only affects post-C89 standards (in C11 VLAs were made optional). Referring to §6.5.3.4/p2 The sizeof and _Alignof operators:

    If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.