Can a const variable be used to declare the size of an array in C?

It’s simply a limitation of the language. The sizes of statically-bounded arrays need to be constant expressions, and unfortunately in C that’s only something like a literal constant or a sizeof expression or such like, but not a const-typed variable.

(As Simon pointed out, since C99 there are also runtime-bounded arrays, or “variable-length arrays”, whose size can be given by the value of any variable. But that’s a different animal.)

You may be interested to hear that the rules are different in C++, where a static const int is indeed a constant expression, and C++11 even adds a new keyword, constexpr, to allow even more general use of constant expressions which encompass more things whose value “could reasonably be determined at compile time”.

Leave a Comment