'variably modified 'stack' at file scope [duplicate]

int const a=9;
int stack[a];
int main()
{
    return 0;
}

The above code gives an error:variably modified 'stack' at file scope

But when I change the code to :

#define b 3
int stack[b];
int main()
{
    return 0;
}

It compiles without error.While both #define and const variable are used for defining the constant identifier then why there is error when I use the const var instead of #define.I searched the similar question but all they gave solution about the error but no reason to it.

Searched about the const and #define and found that sometimes gcc compiler recognizes const as readonly but it is too confusing.

c


Solution 1:[1]

In C language static storage variables can have size defined by the constant expression. Using the variable (even the constant one) as the size is not such a expression.

The error is 100 percent correct.

The second case: proprocessor replaces textually the b with 3 which is the constant expression

Constant expression is something which is evaluated during the compilation. Variable value can be only evaluated runtime.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1