0

Is the following legal?

const int n=10;
static int array[n];

If, yes, then why and how?

chanzerre
  • 2,409
  • 5
  • 20
  • 28
  • The array is not of variable length. `n` is constant expression whose value is known at compile time. – R Sahu Oct 11 '14 at 05:35
  • Array objects declared with the static or extern storage class specifier cannot have a variable length array (VLA) type. see the question Why can't the size of a static array be made variable? [duplicate] – bare_metal Oct 11 '14 at 05:36
  • @R Sahu: That's incorrect. In C language `const` objects do not qualify as compile-time constants. This is an important difference between C and C++ languages. – AnT stands with Russia Oct 11 '14 at 06:13

3 Answers3

4

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.

Community
  • 1
  • 1
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
2
const int n=10;
static int array[n];

This code will encounter an error :

 storage size of ‘array’ isn’t constant static int array[n];
                                        ^

Static memory allocation refers to the process of reserving memory at compile-time before the associated program is executed, unlike dynamic memory allocation or automatic memory allocation where memory is allocated as required at run-time.

const in C donot make that variable available in compile-time.

Statement like this would not generate that error:

static int array[10];

So, the statement that you have written is illegal or it encounter error while compiling the program.

Asis
  • 683
  • 3
  • 23
0

static vars must ve allocated in COMPILE time, and thus their size and initialization value if any MUST be known at compile time. One could argue that using compile time optimizations the n var would/could be replaced with the constant value 10, and thus it might be possible to successfully compile that specific case.

Ron Pinkas
  • 357
  • 2
  • 10