2

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.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415

1 Answers1

6

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Of course I'd also say that in C++ `const int` is considered `constexpr` only if it has `constexpr` initializer. Also, it seems that you don't even need `static` for it (at least it works without on gcc on godbolt). – HolyBlackCat Oct 27 '16 at 14:05
  • Well, actually it's problem in clang, it doesn't correspond to standard. – Борис Степанов Oct 27 '16 at 14:09
  • @БорисСтепанов It's not a problem in clang. Both behaviors are legal from the point of C11 (and C99) standard. A compiler is allowed to treat anything as a constant expression if it can justify it. The standard only says what must be a constant, but allows anything to be a constant expression. – Art Oct 27 '16 at 14:20
  • @HolyBlackCat: Sorry, I misread your comment. – Dietrich Epp Oct 27 '16 at 14:58