
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Does C++ support Variable Length Arrays
- Variable Length Arrays in C and C++
- C program to demonstrate usage of variable-length arrays
- What are variable length (Dynamic) Arrays in Java?
- Initialization of variable sized arrays in C
- Variable Length Argument in C
- C++ Program to Implement Variable Length Array
- Variable length arguments for Macros in C
- Why can a pace or a footstep not be used as a standard unit of length?
- Concatenating variable number of arrays into one - JavaScript
- What are static or fixed length arrays in C#?
- Multiply the fractional part of two Numpy arrays with a scalar value
- Why does the indexing start with zero in C# arrays?
- How to swap two arrays without using temporary variable in C language?
- Finding length of repeating decimal part in JavaScript

Advertisements