3

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.

1 Answer 1

4

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++.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Vlad. I read some where on the net that in C++ array sizes must be constant expressions, not just constant data. so a[1] is not a const expression. But I didn't understand what is const expression. Does it mean that the expression give const value. If that is the case, a[1] also should give const value as per my understanding. Could you please let me know what is const expression?
@kadina it is a compound question. You simply should know that objects defined with specifier constexpr are evaluated at compile time and the compiler can use such values in definitions of arrays.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.