Am presently reading a book named C Primer 5th edition by Barbara E. Moo, Josée Lajoie, and Stanley B. Lippman. While I was reading a topic called array I encountered a problem related to the defining and initialization part of the array, and also a statement which confused me. The statement stated that,
The dimension of an array must be known at the compile time hence the dimension must be a constant expression
The code on the other hand was,
unsigned cnt = 42; // not a constant expression
constexpr unsigned sz = 42; // constant expression
// constexpr see § 2.4.4 (p. 66)
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
When I tried to run the code as,
#include <bits/stdc++.h>
#include<string>
using std::string;
int main()
{
unsigned cnt = 42; // not a constant expression
string bad[cnt]; // error: cnt is not a constant expression
return 0;
}
The following code threw no errors and run succesfully, with the output as,
PS E:\C++> cd "e:\C++\" ; if ($?) { g++ rough1.cpp -o rough1 } ; if ($?) { .\rough1 }
Well my question is that,
Is the following statement and the code error in the book related to the previous versions of cpp? Please explain in detail if possible, both the statement and the code part.