Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize array size from another array value

#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?

like image 782
sova Avatar asked Jan 03 '11 23:01

sova


3 Answers

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];
}
like image 151
Khaled Alshaya Avatar answered Oct 20 '22 01:10

Khaled Alshaya


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

like image 27
Roman L Avatar answered Oct 20 '22 01:10

Roman L


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.

like image 5
grivescorbett Avatar answered Oct 20 '22 02:10

grivescorbett