Reputation: 5384
I am trying to declare an array with const value globally as below. But it is giving compilation error saying array size is not a const value.
const int a[] = {1, 2, 3, 4, 5};
int arr[a[1]];
But if I copy the same lines into a function, it is working fine.
Can you please let me know the differences and why it is not working when I tried to declare global array.
Upvotes: 3
Views: 800
Reputation: 310980
If your compiler supports the new specifier constexpr
of the C++ 2011 Standard then try
constexpr int a[] = {1, 2, 3, 4, 5};
int arr[a[1]];
As for the compiling your code when it is placed in a function then such a code is not C++ compliant. It is a language extension of the compiler you are using. The size of the array shall be a constant expression known at compile time.
In C you may use Variable Length Arrays (VLA). Some copilers included this feature of the C Standard in C++.
Upvotes: 4