0

Consider:

#include <stdio.h>

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:

#include <stdio.h>

#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 is there an error when I use the const var instead of #define?

I searched the similar questions, but they all gave a solution about the error, but no reason to it.

I searched about the const and #define and found that sometimes the GCC compiler recognizes const as read-only, but it is too confusing.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 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 the C language, static storage variables can have a size defined by the constant expression. Using the variable (even the constant one) as the size is not such an expression.

The error is 100 percent correct.

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

A constant expression is something which is evaluated during the compilation. A variable value can only be evaluated at runtime.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0___________
  • 60,014
  • 4
  • 34
  • 74