In C++ Books, Array Bound Must Be Constant Expression, But Why the Following Code Works

Why does a variable size array(VLA) in C++ need to have an automatic (auto) Storage Class?

So, my question is - why can’t we have a VLA in C++ with static storage duration?

First of all VLA's aren't a standard c++ feature.

Well, if you have a compiler supporting VLA's, these cannot be applied for static storage allocation, since it's merely a runtime feature and all static storage allocation is done at compile time.

Why can C++ functions create arrays of variable lengths?

This is not legal code in Standard C++. It compiles thanks to an extension specific to your compiler which supports variable-length arrays, which is a C99 feature.

But again, this is not portable C++. If you need dynamic sizing, you could rewrite your function this way:

#include <vector>

int f(int n)
{
std::vector<int> v(n);
}

Otherwise, make it a template and write it this way:

#include <array>

template<std::size_t N>
int f()
{
std::array<int, N> a;
}

C++ static array like dynamic array

Variable-length arrays are not part of the standard. They can be present as compiler extensions which is the case with GCC. When compiling you are likely to receive a warning of:

warning: ISO C++ forbids variable length array 'a' [-Wvla]

When applied to arrays, the sizeof operator returns the size of the entire array which is the size of the underlying type times the number of elements. The reference states, emphasis mine:

The size of each VLA instance does not change during its lifetime, but
on another pass over the same code, it may be allocated with a
different size.

The official GCC documentation titled 6.19 Arrays of Variable Length states:

These arrays are declared like any other automatic arrays, but with a
length that is not a constant expression. The storage is allocated at
the point of declaration and deallocated when the block scope
containing the declaration exits.

That being said prefer std::vector or std::array to raw (C style) arrays.

Why am I able to create an array of size only known at runtime?

This feature is called "variable length arrays", and is a compiler extension; it is not part of the standard.

If you compile with -pedantic, Clang gives you this warning:

main.cpp:9:14: warning: variable length arrays are a C99 feature [-Wvla-extension]
int array[x];

Don't use this feature if you need your code to be portable.



Related Topics



Leave a reply



Submit