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".
In C, const
is a misnomer for read-only. const
variables can change their value, e.g. it is perfectly okay to declare
const volatile int timer_tick_register; /* A CPU register. */
which you can read and get a different value with each read, but not write to. The language specification thus treats const
qualified objects not as constant expressions suitable for array sizes.
2 major alternatives to VLA: enum
and macros
With enum
:
enum N { N = 5 };int is[N];
This works because enum members are constant expressions: Can enum member be the size of an array in ANSI-C?
With macros:
#define N 5int is[N];
The advantage of enum
s is that enum
s have scope, and are part of the compilation step, so they may lead to better error messages as well.
The advantage of macros is that you have more control over the type of the constants (e.g. #define N 1
vs #define N 1u
), while enum
s are fixed to some implementation defined type: Is the sizeof(enum) == sizeof(int), always? But it doesn't matter much in this case.
Why avoid VLA
- are not in C89, and only optional in C11
- may incur an overhead: Is there any overhead for using variable-length arrays? (likely little)