0

I had read somewhere that C++ requires the size of all statically allocated arrays to be known at compile time. If that information is not known beforehand you either use a pointer (along with dynamic memory allocation) or you use a vector.

I am quite surprised that the following code works perfectly, even though it uses a statically allocated array whose size is not known until runtime.

#include <iostream>
#include <string>

using namespace std;

int main() {
   int input;
   cout << "Enter input: " << endl;
   cin >> input;
   int dimension = input + 4;
   int array[dimension];

   for (int i = 0; i < dimension; i++)
     array[i] = i;

   for(int i = 0; i < dimension; i++)
     cout << array[i] << " ";
     
   cout << endl;

   return 0;
}
Sandeep
  • 1,245
  • 1
  • 13
  • 33
  • 4
    It's using a compiler extension known as VLA, which is not part of the C++ standard. Your code won't compile on e.g.: MSVC – UnholySheep Sep 15 '21 at 19:58
  • *I am quite surprised that the following code works perfectly* -- I am blaming g++ for not removing this default behavior (or clang) for this, but I am now of the opinion new programmers to C++ have two different compilers. In this case gcc/clang as the first compiler, and Visual C++ as the second compiler. If that were to occur, you would see that the code will fail on Visual C++ to compile, with the error that you cannot have arrays with a variable number of elements. Too many newcomers are fooled into using VLA's, when they're not valid C++, all due to using g++ in the default mode. – PaulMcKenzie Sep 15 '21 at 20:21
  • GCC will warn if the '-Wvla' warning is enabled, which is included in the '-pedantic' set. `warning: ISO C++ forbids variable length array ‘array’ [-Wvla]` – PFee Sep 15 '21 at 20:44
  • Note that this is not *static* allocation, but *automatic* allocation. – Fred Larson Sep 15 '21 at 20:58
  • @PaulMcKenzie I fully agree with your statement. Regarding `[…]all due to using g++ in the default mode`, I think another thing that is also very much responsible for it are those code challenging sites and tutorials of educational institutions that are highly ranked but often suggest bad coding styles. Sure if compilers would disable that those sites might also be forced to suggest other things. But I could imagine that those then would suggest adding a flag to enable the VLA extensions. – t.niese Sep 15 '21 at 21:02
  • gcc with default settings is rather non-standard, try `-pedantic` – 463035818_is_not_an_ai Sep 15 '21 at 21:03
  • Or `-pedantic-errors` if you want to absolutely forbid the gcc extensions. – user4581301 Sep 15 '21 at 21:22

0 Answers0