Variable Length Arrays
when I use VC++ (Windows), I cannot build.
An array int a[SIZE]
is created on stack with automatic storage duration.
Then this SIZE
usually must be determined at compile-time in C++.
But your SIZE
is defined without a value as follows:
const int SIZE;
Thus compilers can not know it's value at compile-time and would show compilation error.
So your SIZE
is a dynamic variable.
When I use GCC, build success.
...But some C++ compilers support VLA (variable length arrays) which is a C99 addition and allows declaring C-style arrays on stack with a dynamic length.
VC++ does not support C99 and VLA, but GNU compiler supports VLA as an extension even in C90 and C++.
This is the reason why you can compile the above code by GCC without errors.
If you add -pedantic
(-pedantic-errors
) option to gcc compile command, we can get warnings (errors) for most gcc extensions.
In this case, with this option we should get warning (error) message: ISO C++ forbids variable length array 'a'
.
How to fix the current error ?
(1) If you want to use C-style arrays, one way is making SIZE
a macro as follows. Then compilers can know it's value at compile-time:
#define SIZE 10
class A
{
public:
A() {}
void aaa() { int a[SIZE]; }
};
(2) Defining the value of SIZE
as a static const
variable in the class definition, then compilers again can know it's value at compile-time:
class A
{
static constexpr int SIZE = 10;
public:
A() {}
void aaa() { int a[SIZE]; }
};
(3) C++ provides array functionality by std::vector
and std::array
which might make our code more readable, portable and robust.
I expect that std::array
on stack would be more efficient than std::vector
in your case, because 10 int
s need less memory and std::array
is allocated on stack just only once without causing problems.
This is a solution with std::array
:
#include <array>
class A
{
static constexpr int SIZE = 10;
public:
A() {}
void aaa() { std::array<int, SIZE> a; }
};