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
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
sizeofoperator 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With