C++ Initializing an array with a variable and not a constant expression -
i in process of learning c++ , have been reading c++ primer (5th edition).
in chapter 3.5 talks arrays , initializing them, says arrays must initialized using constant expression.
here example book
unsigned cnt = 42; // not constant expression constexpr unsigned sz = 42; // constant expression int arr[10]; // array of ten ints int *parr[sz]; // array of 42 pointers int string bad[cnt]; // error: cnt not constant expression string strs[get_size()]; // ok if get_size constexpr, error otherwise” excerpt from: stanley b. lippman. “c++ primer, fifth edition.”
however when try using g++ -std=c++11
compiles fine. kind of confused whether mistake in book or has standard been modified since writing of book though book states uses c++ 11.
here actual code using compiles , runs 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 tried this
int var = 2; int size = var; int int_arr[size];
and works.
if has explanation or why works though states shouldn't appreciate it.
thanks!
variable length arrays extensions built compiler c++11 , not standard, if compile -wvla
flag see compiler emit error code.
you better of using std::vector
dynamic arrays instead. if not familiar how use suggest looking around online. there plenty of sources go detail how use std::vector
, how works.
Comments
Post a Comment