The feature that the code snippet requires is called variable length arrays (VLAs). Support for this feature in the C or C++ language depends on the compiler and the version of the standard.
- C99 supports VLAs as standard.
- Versions earlier than C99 (includes C90) do not support VLAs as standard, but some compilers may implement it as a language extension.
- C11 makes VLAs an optional feature.
- C++14 supports a restricted variant of VLAs called dynamic arrays.
- Versions earlier than C++14 (includes C++11, C++03, and C++98) do not support VLAs as standard, but some compilers may implement it as an extension.
In particular, GCC implements VLAs as a language extension for C90 and C++, and apparently www.compileonline.com uses GCC as the compiler (version 4.7.2 as of this writing). No version of the Visual C++ compiler implement VLAs.
Herb Sutter talks about C++14's dynamic array feature:
In the language, draft C++14 now allows stack-based arrays to have a size determined at run time:
void f(std::size_t n)
{
int a[n];
...
}
Note that this is not the same as C99 variable length arrays (VLAs),
and that the C11 standard has made VLAs conditionally-supported so
that they are no longer part of portable C required in a conforming C
compiler. In particular, C++ explicitly not does support the following
features from C99 VLAs which C++ feels are not desirable:
- multidimensional arrays, where other than the top level has a runtime
bound (in analogy, the array form of new expressions doesn’t support
that either)
- modifications to the function declarator syntax
sizeof(a)
being a runtime-evaluated expression returning the size of a
typedef int a[n];
evaluating n
and passing that through the typedef
If you want C++ code that works in pretty much any version of C++, consider using std::vector
instead:
#include <vector>
int main()
{
int var = function(a); // Assume function() has been defined.
std::vector<int> num(var); // Creates a vector with var number of elements.
// ...
int num1 = num[1]; // You can access elements in vectors just like arrays.
num[1] += 10;
// ...
}