Is the following legal?
const int n=10;
static int array[n];
If, yes, then why and how?
Note that in C language const
objects do not qualify as constants. They cannot be used to build constant expressions. In your code sample n
is not a constant in the terminology of C language. Expression n
is not an integral constant expression in C.
(See "static const" vs "#define" vs "enum" and Why doesn't this C program compile? What is wrong with this? for more detail.)
This immediately means that your declaration of array
is an attempt to declare a variable-length array. Variable length arrays are only allowed as automatic (local) objects. Once you declare your array with static storage duration, the size must be an integral constant expression, i.e. a compile-time constant. Your n
does not qualify as such. The declaration is not legal.
This is the reason why in C language we predominantly use #define
and/or enum
to introduce named constants, but not const
objects.