Cannot compile static array with fixed size [dupli

2020-04-19 17:59发布

问题:

Minimal code example:

#include <stdio.h>
int main()
{
    const int a = 5;
    static int b[a];
    return 0;
}

Looks fine, eh? Variable a is constant. Works with 4.4 too.

gcc -v
gcc version 6.2.1 20160830 (GCC)
gcc 1.c
1.c: In function ‘main’:
1.c:6:16: error: storage size of ‘b’ isn’t constant
     static int b[a];

Btw, clang compiles this code well.

回答1:

Arrays declared as static or at file scope (i.e. having static storage duration) cannot be variable length arrays:

From section 6.7.6.2 of the C standard:

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.

Even though the length is specified by a const int, it is not considered a constant expression. Even using a size of type static const int doesn't satisfy this requirement.

Note that this is different in C++, where a static const int is considered a constant expression. C++11 also defines the constexpr keyword for this purpose.