0

I'm a beginner in c++, and everything worked fine until a couple a days ago. I tried to run a code but it gave me this error: "ISO c++ forbids variable lenght array 'v' [-Wvla]" (I haven't modified anything from settings).

Here is the code:

#include <iostream>

using namespace std;

int n,i;

int main()
{
    cin>>n;
    int v[n];
    for(i=0;i<n;i++)
    {
        v[i]=i;
    }
    for(i=0;i<n;i++)
    {
        cout<<v[i]<<' ';
    }
}

Also, I've tried to run the program on the online compiler and it works ok. If I need to show you something just tell me.

  • 1
    You are yet another victim of the g++ compiler's default behavior. This `int v[n]` is not valid C++. Try your code with Visual Studio, and you will get the error. – PaulMcKenzie Jun 03 '20 at 12:47
  • The size of the array may only be a compile-time known constant. If you read that from the console, it's a runtime value, so not possible. You should either use a std::vector (preferred solution), or allocate memory for the array dynamically with `new int[n]` (avoid solution). – Marius Bancila Jun 03 '20 at 12:49
  • Also: [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Jun 03 '20 at 12:49
  • It's hard to believe that it worked a couple of days ago... – Hack06 Jun 03 '20 at 12:52

1 Answers1

2

Why do I get this warning: ISO c++ forbids variable lenght array 'v' [-Wvla]

Because you create an automatic array of size n, where n is not a compile time constant value. Creating an automatic array of non-compile time constant size is not allowed in C++. The shown program is ill-formed.

Compilers are allowed to not compile an ill-formed program, and they are required to show a diagnostic message such as the one that you quoted.

If you want an array of runtime size, then you need to create a dynamic one. Simplest way to achieve that is to use std::vector.

eerorika
  • 232,697
  • 12
  • 197
  • 326