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;
}
6
  • 2
    It is accepted as a GCC extension (or a Clang one). But VLAs are not in C++17 Commented Jul 7, 2018 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. Commented Jul 7, 2018 at 20:18
  • Is accepted also compiling with "-ansi -pedantic"? Commented Jul 7, 2018 at 20:18
  • 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. Commented Jul 7, 2018 at 21:10
  • 1
    See Does “int size = 10;” yield a constant expression? for more details Commented Jul 8, 2018 at 1:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"heap memory is used instead of stack memory" - are you sure?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.