Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of non-constant size: Why does this even work? [duplicate]

#include <iostream>
using namespace std;

int main(){
    int n;
    cout<<"Enter the size :";
    cin>>n;
    int array[n];  // I've worked some outputs and it works 
    return 0;
}

Is this some kind of dynamic allocation?
Why doesn't it even gives an error for 'n' to be a "const"?

Also, writing cout << array[n+5]; doesn't result in an compile time or runtime error.

I'm using Dev-C++.

like image 471
Lucky Avatar asked Oct 20 '22 12:10

Lucky


1 Answers

Apparently one can declare variable length arrays in C99, and it seems GCC accepts then for C++ also.

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression.

You learn something every day .. I hadn't seen that before.

like image 89
harmic Avatar answered Oct 29 '22 21:10

harmic