6
#include<iostream> 
using namespace std; 

const int vals[] = {0, 1, 2, 3, 4}; 

int newArray[ vals[2] ]; //"error: array bound is not an integer constant"

int main(){
    return vals[2];
}

//returns 2 if erroneous line is removed

Why doesn't this work?

3 Answers 3

12

Unfortunately you can't do that in standard C++ because vals[2] is not a constant expression! In the coming standard you would have constexpr(implemented in g++ 4.6) to request compile-time evaluation easily:

#include<iostream> 
using namespace std; 

constexpr int vals[] = {0, 1, 2, 3, 4}; 

int newArray[ vals[2] ]; // vals[2] is a constant expression now!

int main(){
    return vals[2];
}
1
  • The first sentence should now be "You can do that in standard C++ (ever since C++11); you only could not do it in C++03 or earlier" (or something like that), if I understand correctly. Dec 30, 2020 at 7:13
8

It's possible that the value of a const expression is not even known at compile time. For example, you can initialize a constant with something returned from a function, like

const int size = rand(); // random size

So it is not that constant as you might think

0
5

The C++ compiler can only allocate an array with a size known at compile time. If you want to allocated a variable size piece of memory, use the new operator.

2
  • 7
    or even better yet, std::vector.
    – Ben Voigt
    Jan 3, 2011 at 23:55
  • 3
    Looks like an answer to some other question to me
    – Roman L
    Jan 4, 2011 at 0:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.