C Arrays – Can Array Length in Declaration Be Non-Constant?

arraysc++constant-expressiondeclarationsyntax

I am a bit confused about array declaration in C. I know that it's possible to do this:

int a[20];  // Reserved space for 20 int array
int b[] = {32, 431, 10, 42};  // Length in square brackets is auto-calculated
int *c = calloc(15, sizeof(int));  // Created a pointer to the dynamic int array

But is it possible to do this?:

int my_array[sizeof(int) * 5];

Is it a valid code, or an array length should be a constant expression (in ANSI C)?

Best Answer

This declaration

int my_array[sizeof(int) * 5];

does not declare a variable length array because the expression sizeof(int) * 5 is a constant integer expression. So even your compiler does not support variable length arrays you may use such a declaration.

From the C Standard (6.6 Constant expressions)

6 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, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof operator.

and (6.7.6.2 Array declarators)

4 If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations or type names with function prototype scope; such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)

A declaration of a variable length array can look like

const int n = 5;
int my_array[sizeof(int) * n];

The support of variable length arrays is optional in C11 and higher.

Related Question