Search code examples
c++gccvariable-length-array

Why doesn't this code generate an error on using a variable array size?


The code below should generate an error, since there is no way that the compiler can know the array size during compilation.

int f;
std::cin >> f;
int c[f];
c[100] = 5;

I am compiling with gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2 and it doesn't just compile, but it runs somehow.

How does it happen?


Solution

  • C99 accepts variable length arrays, and gcc accepts them as an extension in C90 and C++.

    Using -pedantic or -Wvla turns this into a warning in C++ code, and -Werror=vla turns it into an error.