chanzerre
chanzerre

Reputation: 2429

Static arrays with variable length

Is the following legal?

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

If, yes, then why and how?

Upvotes: 0

Views: 3225

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320381

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.

Upvotes: 4

Asis
Asis

Reputation: 733

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.

Upvotes: 2

Ron Pinkas
Ron Pinkas

Reputation: 367

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.

Upvotes: 0

Related Questions