0

I set the size of the array after compiling the program without using dynamic allocation. I can't understend why this code is working. I can guess that compiler create the array with length of array = 0, because variable length is equal to zero.

#include <iostream>
using namespace std;

int main()
{
    cout << "Enter length of the array: ";
    int length;
    cout << length << endl;
    cin >> length;
    int array[length] = {};
    for(int i = 0; i < length; i++)
    {
        array[i] = i;
        cout << array[i] << endl;
    }

    return 0;
}
Pablo
  • 9
  • 1
  • 3
    This isn't valid C++. Some compilers might accept it if they provide an extension that allows it. In this case GCC have an extension for variable length arrays enabled by default. – François Andrieux Nov 10 '21 at 17:53
  • If your question is "How do they work?" you should ask how variable length arrays work in the C language. If your C++ compiler allows VLAs. it's likely added as a compiler-specific language extension because the matching C compiler is required to implement them. [How does GCC implement variable-length arrays?](https://stackoverflow.com/questions/21182307/how-does-gcc-implement-variable-length-arrays) – Drew Dormann Nov 10 '21 at 17:57
  • (1) `length` is initially undefined in the code snippet, there is no guarantee that it is equal to zero. (2) The compiler doesn’t create a zero-length array; it simply supports a language extension that lets it accommodate variable-length arrays on the stack. Build it with `-Wall -Wextra -pedantic` to get all relevant warnings. (3) Just for fun, you can check your stack size limit (`ulimit -s`) and then set the array size to something greater than that; you will see that the array is (indeed) on the stack. (4) `using namespace std;` is an antipattern; just don’t do that. – Andrej Podzimek Nov 10 '21 at 19:12
  • Related: [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/) – Remy Lebeau Nov 10 '21 at 21:13

0 Answers0