0

I recently changed my C++ compiler, and I am experiencing this strange error that says ISO C++ forbids variable length array. I distinctly remember that this error was not encountered by my previous compiler. Here is my code snippet that I wrote just to check the reliability of this new compiler.

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin>>n;
    int a[n];
    for(int i=0;i<n;i++)
        cin>>a[i];
    for(int i=0;i<n;i++)
        cout<<a[i]<<" ";
    return 0;
}


In function 'int main()':
test.cpp:8:9: error: ISO C++ forbids variable length array 'a' [-Wvla]
int a[n]={0};

You see even when user is taking input in 'n', the compiler states that the array is having variable length. Suggestions regarding other compiler version are also welcome!

zean_7
  • 336
  • 3
  • 12
  • 3
    It's exactly what the error says. Standard C++ forbids arrays with lengths that aren't known at compile time. Some compilers have extensions that allow VLAs, but they usually aren't a good idea. – eesiraed Jan 04 '20 at 06:04
  • 3
    [Variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) are not part of C++. Some compilers might add it as a non-standard extension. Use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) instead. – Some programmer dude Jan 04 '20 at 06:05

3 Answers3

2

Replace the VLA with a std::vector:

#include <iostream>
#include <vector>

int main()
{
    int n;
    std::cin>>n;
    std::vector<int> a(n);  // was VLA: int a[n];
    for(int i=0;i<n;i++)
        std::cin>>a[i];
    for(int i=0;i<n;i++)
        std::cout<<a[i]<<" ";
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
1

Your new compiler is correct: variable-length arrays are not allowed in standard C++! (GNU g++ allows them as an extension). See here: Why aren't variable-length arrays part of the C++ standard?

You should modify your code to use the std::vector type, instead:

#include <iostream>
#include <vector> // Definitions for the std::vector types
//using namespace std; // This can cause problems - better only "using" specifics:
using std::cin;
using std::cout;

int main()
{
    size_t n; // You CAN use "int" but "size_t" is more accurate here
    cin >> n;
//  int a[n]; // Forbidden in standard C++
    std::vector<int> a(n); // Declare "a" as a vector with "n" elements
    for (size_t i = 0; i < n; i++)
        cin >> a[i]; // You can still use the "[i]" syntax to access the elements
    for (size_t i = 0; i < n; i++)
        cout << a[i] << " ";
    return 0;
}

Feel free to ask for further clarification and/or explanation.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

The code is not valid in standard C++. As per C++ standard, array size must be a constant expression. Variable lenghth arrays are not allowed in C++ because C++ provides std::vector for that. C standard allows VLA(variable length arrays) while C++ does not.

H S
  • 1,211
  • 6
  • 11