In C, this declaration:
const int NUM_FOO = 5;
doesn't make NUM_FOO
a constant expression.
The thing to remember (and yes, this is a bit counterintuitive) is that const
doesn't mean constant. A constant expression is, roughly, one that can be evaluated at compile time (like 2+2
or 42
). The const
type qualifier, even though its name is obviously derived from the English word "constant", really means "read-only".
Consider, for example, that these are a perfectly valid declarations:
const int r = rand();
const time_t now = time(NULL);
The const
just means that you can't modify the value of r
or now
after they've been initialized. Those values clearly cannot be determined until execution time.
(C++ has different rules. It does make NUM_FOO
a constant expression, and a later version of the language added constexpr
for that purpose. C++ is not C.)
As for variable length arrays, yes, C added them in C99 (and made them optional in C11). But as jamesdlin's answer pointed out, VS2019 doesn't support C99 or C11.
(C++ doesn't support VLAs. This: const int NUM_FOO = 5; int foo[NUM_FOO];
is legal in both C99 and C++, but for different reasons.)
If you want to define a named constant of type int
, you can use an enum
:
enum { NUM_FOO = 5 };
or an old-fashioned macro (which isn't restricted to type int
):
#define NUM_FOO 5
jamesdlin's answer and dbush's answer are both correct. I'm just adding a bit more context.