jeudi 27 juillet 2017

C++ Initializing an array with a variable and not a constant expression

I am currently in the process of learning C++ and have been reading C++ Primer (5th Edition).

In chapter 3.5 which talks about arrays and initializing them, it says arrays must be initialized using a constant expression.

Here is an example from the book

unsigned cnt = 42; // not a constant expression
constexpr unsigned sz = 42; // constant expression
int arr[10]; // array of ten ints
int *parr[sz]; // array of 42 pointers to int
string bad[cnt]; // error: cnt is not a constant expression
string strs[get_size()]; // ok if get_size is constexpr, error otherwise”

Excerpt From: Stanley B. Lippman. “C++ Primer, Fifth Edition.” 

However when I try this using g++ -std=c++11 everything compiles just fine. So I am kind of confused as whether this is just a mistake in the book or has the standard been modified since the writing of the book even though the book states it uses C++ 11.

Here is the actual code I am using which compiles and runs perfectly fine

unsigned int cnt = 42; // not constant expression
constexpr unsigned int sz = 42; // constant expression

int arr[10]; // array of 10 ints
int *parr[sz]; // array of 10 int pointers
string bad[cnt];

I even tried something like this

int var = 2;
int size = var;
int int_arr[size];

And this also works.

If anyone has an explanation or just why this works even though it states it shouldn't I would appreciate it.

Thanks!

Aucun commentaire:

Enregistrer un commentaire