Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set array size with const member variable?

I tried to set array size with const member variable like below

class A {
  const int SIZE;

  A() : SIZE(10) {}
  void aaa() { int a[SIZE]; }
};

I cannot build

a[SIZE]

like this expression.

When I use GCC, build success. But when I use VC++ (Windows), I cannot build.

The error message is "'this' cannot be used in a constant expression"

How to set array size with const member variable?

like image 764
Dayamre Avatar asked Oct 19 '25 11:10

Dayamre


1 Answers

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 ints 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; }
};
like image 102
Hiroki Avatar answered Oct 21 '25 01:10

Hiroki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!