0

Given that user input is taken at runtime but array is created during compile time. How and why does this piece of code work?

#include <iostream>
using namespace std;
int main(){
    int n;
    cin>>n;
    int arr[n]; //Why can I use this statement to create an array?
}
François Andrieux
  • 28,148
  • 6
  • 56
  • 87

1 Answers1

1

It's a non-standard extension, supported by gcc and clang.

It works by allocating space on the stack at the point the array is declared, a bit like alloca.

The memory allocated is automatically freed (by adjusting the stack pointer) when the function returns (or arr goes out of scope).

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48