1

For example, if you have some code that takes an integer as input and then declare an array of that size, like this:

#include <iostream>
using namespace std;
int main(){
    size_t NUM;
    cin >> NUM;
    size_t array[NUM];
    //do whatever
    return 0;
}

How does this not give an error when compiling? The compiler should set aside a specific part of memory for the array, but how can it do that when the size is NUM, and is not known during compilation? Does the compiler automatically convert it to a dynamic array with new?

I am using g++ 7.3.0 compiler.

Thank you!

WZHANG
  • 21
  • 5
  • 3
    `array` is not a `static` variable in your example. It is a local variable in the `main()` function. The storage for it is not allocated until `main()` is called. – Solomon Slow Aug 08 '18 at 20:11
  • 3
    It will give an error (or at least a warning) if you use the correct compiler options - for example, `-pedantic` with GCC. –  Aug 08 '18 at 20:13
  • 6
    ... and arrays of dynamic size, i.e. where `NUM` is not a `constexpr`, are not supported by C++ standard. Some compilers provide extensions (e.g. gcc), but these extensions are still not standard. – Stephan Lechner Aug 08 '18 at 20:14
  • 2
    The term you are looking for is VLA. They started as a gcc extension, got standardized in C but not in C++. g++ will accept them in C++ as well with all but most restrictive command line options. – Matteo Italia Aug 08 '18 at 20:21
  • 2
    Possible duplicate of [Array size at run time without dynamic allocation is allowed?](https://stackoverflow.com/questions/737240/array-size-at-run-time-without-dynamic-allocation-is-allowed) – Justin Aug 08 '18 at 20:40

0 Answers0