0

C++ Primer (5th edition) states that when an array is initialised with a size, the size provided has to be a constexpr, like this:

int arr[10];

// or

constexpr size_t sz = 10;
int arr[sz];

However, this code compiles just fine for me:

size_t sz = 10;
int arr[sz];

So, is the constexpr really needed?

Train Heartnet
  • 785
  • 1
  • 12
  • 24

1 Answers1

2

Compiling (g++ -pedantic --std=c++11 -o t t.cpp) in pedantic mode gives:

t.cpp:5:8: warning: variable length arrays are a C99 feature [-Wvla-extension]
int arr[sz];
       ^
1 warning generated.

You may even reject the code with -pedantic-errors.

[C++11: 8.3.4/1]: In a declaration T D where D has the form

D1 [ constant-expressionopt ] attribute-specifier-seqopt [..]

Thus any constant is acceptable, constexpr or const variables.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69