0

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]={};
perror
  • 7,071
  • 16
  • 58
  • 85
wenfeng
  • 177
  • 1
  • 7
  • In the first, `f` is a variable-length array. Those cannot be initialised. In the second, it's not a VLA, hence can be initialised. – Daniel Fischer May 08 '13 at 21:27
  • 1
    See http://stackoverflow.com/questions/1887097/variable-length-arrays-in-c for a discussion of why you are limited to fixed length arrays – OOhay May 08 '13 at 21:30

2 Answers2

2

Array initializers need to be const.

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

Connor Hollis
  • 1,115
  • 1
  • 7
  • 13
0

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

Marc Claesen
  • 16,778
  • 6
  • 27
  • 62