wenfeng
wenfeng

Reputation: 177

C++ 2d array initialization

The following line doesn't work:

int n1=10,v1=10;  
int f[n1][v1]={};
error: variable-sized object ‘f’ may not be initialized

But the line below works, why?

const int n1=10,v1=10;  
int f[n1][v1]={};

Upvotes: 0

Views: 563

Answers (2)

Connor Hollis
Connor Hollis

Reputation: 1155

Array initializers need to be const.

An int value can change where as a const int value will remain constant throughout the entire program.

Upvotes: 2

Marc Claesen
Marc Claesen

Reputation: 17026

In the second example, n1 and v1 are known to be compile-time constants. In the first example, they may not be.

Upvotes: 0

Related Questions