When I was reading about the array initialization in this tutorial. I found out this note.
type name [elements];
NOTE: The e
The declaration T a[N]
requires that N
be a converted constant expression.
Converted constant expression is an expression implicitly converted to prvalue of type T, where the converted expression is a core constant expression. If the literal constant expression has class type, it is contextually implicitly converted to the expected integral or unscoped enumeration type with a constexpr user-defined conversion function.
An int literal such as 5
is a prvalue, so can be used in the declaration T a[5]
, but an lvalue, for example int n = 5
cannot be used in the declaration T a[n]
, unless the lvalue under-goes an implicit lvalue-to-rvalue conversion where the lvalue:
a) has integral or enumeration type, is non-volatile const, and is initialized with a constant expression, or an array of such (including a string literal)
b) has literal type and refers to a non-volatile object defined with constexpr or to its non-mutable subobject
c) has literal type and refers to a non-volatile temporary, initialized with a constant expression
Therefore the following are valid:
const int n = 5;
int a[n];
constexpr int n = 5;
int a[n];
Please check if the following answers help in giving you clarity about this.
Static array vs. dynamic array in C++
Static arrays are created on the stack, and necessarily have a fixed size (the size of the stack needs to be known going into a function): int foo[10];
Dynamic arrays are created on the heap. They can have any size, but you need to allocate and free them yourself since they're not part of the stack frame: int* foo = new int[10]; delete[] foo;
You don't need to deal with the memory management of a static array, but they get destroyed when the function they're in ends
Array size at run time without dynamic allocation is allowed?
C99 standard (http://en.wikipedia.org/wiki/C99) supports variable sized arrays on the stack. Some of the compilers might implement these standards and support variable sized arrays.
You may use :
int array[42];
but not
int n;
std::cin >> n;
int array[n]; // Not standard C++
the later is supported as extension by some compiler as VLA (Variable length array)