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]={};
2
  • 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. Commented May 8, 2013 at 21:27
  • 1
    See stackoverflow.com/questions/1887097/variable-length-arrays-in-c for a discussion of why you are limited to fixed length arrays Commented May 8, 2013 at 21:30

2 Answers 2

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.

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

2 Comments

I see, Could I put const int parameters? void test1(const int& n){ int f0[n]; int f1[n]={}; for(int i=0; i<n; i++)cout<<f0[i]<<" "<<f1[i]<<endl; }
It doesn't seem so, this was tested with G++ 4.5.3 under Cygwin: codepaste.net/gwnck4
0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.