Why aren't variable-length arrays part of the C++ standard?


Having to create a potential large array on the stack, which usually has only little space available, isn't good. If you know the size beforehand, you can use a static array. And if you don't know the size beforehand, you will write unsafe code. Variable-length arrays can not be included natively in C++ because they'll require huge changes in the type system.

An alternative to Variable-length arrays in C++ is provided in the C++ STL, the vector. You can use it like −

Example

#include<iostream>
#include<vector>
using namespace std;

int main() {
   vector<int> vec;
   vec.push_back(1);
   vec.push_back(2);
   vec.push_back(3);
   vec.push_back(4);
   vec.push_back(5);
   // ...

   // To iterate over it:
   for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++) {
      cout << *it << endl;
   }
   return 0;
}

Output

This will give the output −

1
2
3
4
5

Updated on: 24-Jun-2020

356 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements