We have the following non-conforming C code with the definitions at file scope:
const int n = 5;
int m = n; // n is not a constant expression
It compiles without a warning with gcc-10.3.0 and flags -c -Wall -pedantic -std=c99
.
It's fine because of 6.6p10
An implementation may accept other forms of constant expressions.
Though a warning should be raised due to -pedantic
option.
However, the following code (also at file scope):
const int n = 5;
int A[n];
fails with a compilation error:
error: variably modified ‘A’ at file scope
And it's strange because assuming treating n
as constant expression the declaration above should be equivalent to:
int A[5];
Neither Variable Modified types (i.e. VLA) at file scope nor using non-const values in an initializer for variables with static storage is allowed by C standard.
What is the reason of treating n
as a constant expression in one context while not in the other?
Edit
This question is GCC specific.
This question is not a duplicate of stackoverflow.com/q/59065111/4989451 because I am not asking why no warning is raised but why "extended" constant expression is treated differently in "size expression" and "initializer".
Edit 2
It looks that I have incorrectly assumed that GCC treats n
as a constant expression. It rather accepts n
as an initializer for objects with static storage. I was tricked by the lack of warning about non-constant when compiling in "pedantic" mode. It's likely a compiler bug.
With such an interpretation, this question is indeed a duplicate.
Edit3
This question and answers looks very related: Why does gcc/clang handle code slightly differently? (Example given)