0

Is the following legal?

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

If, yes, then why and how?

3
  • The array is not of variable length. n is constant expression whose value is known at compile time. Commented Oct 11, 2014 at 5: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] Commented Oct 11, 2014 at 5: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. Commented Oct 11, 2014 at 6:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.