5
#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++.

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
Lucky
  • 61
  • 3
  • 1
    +1 for asking not why it doesn't work, but why it works when it shouldn't. – Mark Garcia Mar 09 '14 at 06:16
  • 3
    It's not dynamic. `n` `int`s are allocated on the stack, and they're deallocated at the end of the scope. It's not supported by the standard, but g++ permits it as an extension. Note also that it's allowed in C99. – Brian Bi Mar 09 '14 at 06:16
  • Well this is not standard way to code, but it would be hard to come up with a compiler grammar to intentionally make it not work :P – miushock Mar 09 '14 at 06:19
  • @NiklasB. It works fine with `-std=c++11`. To disable GNU extensions must use `-pedantic` or better `-pedantic-errors`. – Ivan Aksamentov - Drop Mar 09 '14 at 06:25
  • here is some explanation: http://stackoverflow.com/questions/2863347/declaring-the-array-size-with-a-non-constant-variable – KedarX Mar 09 '14 at 06:26
  • @miushock grammar has nothing to do with it, it is not a syntax error, but it is a constraint violation (in C++ the expression inside the brackets must be constant). It would be easy for the compiler to issue an error, but the compiler developers chose to implement this extension. – M.M Mar 09 '14 at 06:29
  • @LưuVĩnhPhúc It's definitely a pretty exact duplicate. – Niklas B. Mar 09 '14 at 06:34
  • As for `cout< – Niklas B. Mar 09 '14 at 06:35
  • @Lucky -- Dev-C++ is not a compiler. The compiler that Dev C++ uses is g++ (and a very old version). Dev C++ is just an integrated environment so that it becomes easier to use the g++/gcc tools. – PaulMcKenzie Mar 09 '14 at 06:48

1 Answers1

3

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.

harmic
  • 28,606
  • 5
  • 67
  • 91