0

I knew there have been several questions about variable length array (VLA). I thought the general conclusion is that VLA is not supported. But the following code will compile just fine. Anyone can explain it?

#include <iostream>
#include <vector>

using namespace std;

void func(vector<int> v){
    int arr[v.size()] = {0};
    int b = 4;
    return;
}

void func2(int n)
{
    int arr[n];
}

int main()
{
  vector<int> v = {1,2,3};
  func(v);
  func2(10);
  int len = 8;
  int arr[len] = {0};
  return 0;
}
Z-Jiang
  • 189
  • 2
  • 10
  • 2
    It is accepted as a GCC extension (or a Clang one). But VLAs are not in C++17 – Basile Starynkevitch Jul 07 '18 at 20:17
  • Just don't do it. It's dangerous and not standard. Some compilers may allow it since they already have that C99 functionality. – DeiDei Jul 07 '18 at 20:18
  • Is accepted also compiling with "-ansi -pedantic"? – max66 Jul 07 '18 at 20:18
  • Does it mean that Intel compiler will not accept it? – Z-Jiang Jul 07 '18 at 20:22
  • 2
    You cannot prove the correctness of a C++ program "by experiment". The language simply doesn't allow that. A program is correct if it follows the language's rules, and a correct program can be compiled and run. Nothing can be said about the converse. – Kerrek SB Jul 07 '18 at 21:10
  • 1
    See [Does “int size = 10;” yield a constant expression?](https://stackoverflow.com/q/21273829/1708801) for more details – Shafik Yaghmour Jul 08 '18 at 01:13

1 Answers1

2

It shows error message "variable-sized object may not be initialized" using compiler g++ 4.8.4 and C++11.

Some compilers partially support this kind of array definition as an extension. See this link. However, it is not in C++ standard.

When you allocate an array on stack memory you must state its length at compile-time. If you want to have a variable length array, you must allocate it on the heap memory.

Ebrahim
  • 109
  • 1
  • 3
  • "heap memory is used instead of stack memory" - are you sure? – aschepler Jul 08 '18 at 05:51
  • I was wrong. In some compilers it is supported with some limitations and the memory is allocated in stack memory. I edited the answer thanks to your question. – Ebrahim Jul 08 '18 at 08:22