I tried to write a c program as below?
const int x = 5;
int main()
{
int arr[x] = {1, 2, 3, 4, 5};
}
This is giving warnings when I tried to compile with gcc as below.
simple.c:9: error: variable-sized object may not be initialized.
But the same is allowed in C++. When I pass x as array size, why x is not treated as constant?
Best Answer
In C
const
doesn't mean "constant" (i.e., evaluable at compile time). It merely means read-only.For example, within a function, this:
is perfectly valid.
The name of an object defined as
const int
is not a constant expression. That means that (in C prior to C99, and in all versions of C++) it can't be used to define the length of an array.Although C99 (and, optionally, C11) support variable-length arrays (VLAs), they can't be initialized. In principle, the compiler doesn't know the size of a VLA when it's defined, so it can't check whether an initializer is valid. In your particular case, the compiler quite probably is able to figure it out, but the language rules are designed to cover the more general case.
C++ is nearly the same, but C++ has a special rule that C lacks: if an object is defined as
const
, and its initialization is a constant expression, then the name of the object it itself a constant expression (at least for integral types).There's no really good reason that C hasn't adopted this feature. In C, if you want a name constant of an integer type, the usual approach is to use a macro:
Note that if you change the value of
LEN
, you'll have to re-write the initializer.Another approach is to use an anonymous
enum
:The name of an enumeration constant is actually a constant expression. In C, for historical reasons, it's always of type
int
; in C++ it's of the enumeration type. Unfortunately, this trick only works for constants of typeint
, so it's restricted to values in the range fromINT_MIN
toINT_MAX
.