Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ books, array bound must be constant expression, but why the following code works?

Tags:

c++

#include <iostream>
using namespace std;

int main(){
    int n=10;
    int a[n];

    for (int i=0; i<n; i++) {
        a[i]=i+1;
        cout<<a[i]<<endl;
}
    return 0;
}

worked fine in Xcode4 under Mac

as said in books, it should be wrong, why?

so confused~

like image 825
f1chen Avatar asked May 10 '11 08:05

f1chen


2 Answers

This a a C99 feature called VLA which some compilers also allow in C++. It's allocation on stack, just as it would be with int a[10].

like image 139
Erik Avatar answered Oct 26 '22 10:10

Erik


That is C99 feature that allows VLA (variable length array).

Compile it with g++ -pedantic, I'm sure that wouldn't compile.

like image 43
Nawaz Avatar answered Oct 26 '22 09:10

Nawaz