Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying dimension of array in function and outside function does not give same result

This compiles fine under C99

const int DIM;

int main() {
    int tab[DIM];
}

while the following gives the error

int tab[DIM];

int main() {
}

error: variably modified tab at file scope

Why?

I know how to fix it :

#define DIM  10

But this does not provide the answer to my question Thanks for your reply

like image 738
axel Avatar asked Feb 21 '26 01:02

axel


1 Answers

Sizes of variable length arrays are calculated at run-time.

Read for example the following quote from the C 2024 Standard (6.5.4.5 The sizeof and alignof operators):

The sizeof operator yields the size (in bytes) of its operand, which can 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.

or (6.7.7.3 Array declarators):

If an identifier is declared as having a variably modified type, it shall be an ordinary identifier (as defined in 6.2.3), have no linkage, and have either block scope or function prototype scope. If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.

Pay attention to that variables declared at file scope have static storage duration.

By the way in the first program you shall initialize the variable DIM because it has the qualifier const and in the second program you missed its definition.:)

In C variables declared with the qualifier const are not constant expressions that are evaluated at compile time.

Thus the first progam is compiled successfully because the declared array has automatic storage duration. Memory for the array is allocated at run time.

The second program is not compiled because the declared at file scope variable length array has static storage duration.

If you will include the directive

#define DIM  10

then the declared array will not be a variable length array because its size is specified with a constant expression that is evaluated at compile time.

like image 192
Vlad from Moscow Avatar answered Feb 22 '26 15:02

Vlad from Moscow