0
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.

Evg
  • 23,109
  • 5
  • 38
  • 74
  • The array dimensions for static arrays must be *integer constant expressions* that resolve at compile time. It is very well defined what is and what isn't an integer constant expression. Especially, evaluation of the *value* `const int` is *not* allowed in integer constant expressions. – Antti Haapala -- Слава Україні Jul 06 '19 at 09:17
  • what are integer constant expressions and what is the difference between integer and integer constant expression – Utkarsh Ghosh Jul 06 '19 at 09:38
  • From the C 2011 standard, 6.6, Constant Expressions: “An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, `sizeof` expressions whose results are integer constants, `_Alignof` expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or `_Alignof` operator.” – John Bode Jul 06 '19 at 12:43

1 Answers1

0

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.

0___________
  • 47,100
  • 4
  • 27
  • 62