The code is clean C99 code. C99 added support for VLAs (variable length arrays). C11 made the support optional. Your code compiles cleanly, except that the printf()
should use %zu
rather than %d
to print the value from sizeof()
.
C11 §6.5.3.4 The sizeof
and _Alignof
operators says:
¶2 The sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. 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.
In your code, the size is evaluated at run-time. You could have code such as:
printf("Enter the array size: ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 1024)
{
fprintf(stderr, "Did not get a valid size\n");
exit(EXIT_FAILURE);
}
int array[n];
and then printing the size will still be correct — the size is calculated (evaluated) at run-time. But that's only for VLAs.
VLAs may not be initialized — the standard is clear about that, too — §6.7.9 Initialization says:
¶3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.
You cannot write an initializer for a VLA. That's a 'constraint'; it is mandatory that the compiler complains about the abuse of the standard.