I'm just jumping into C++, coming from C
In C (89/90), a const
is not actually a constant (as opposed to a #define
'd, enum
, or literal), but rather read-only once set. I.e, I can:
const int x = rand();
and that's fine - the point being x
isn't known until runtime. Hence, I can't
int arr[x]; // error - x is not a compile-time constant
Then, one of the C standards (99?) went ahead and allowed for variable-length arrays. Although I normally code against the ANSI standard in C, this has actually had an impact now that I am trying to pickup C++11.
As far as I know, C++ does not allow for variable-length arrays. However, many compilers allow it as an extension (GCC ?). The problem is, now that I am trying to learn C++11, I can't tell if what I'm coding is valid C++, or C++ extended with C99-compatibility. Ex:
std::default_random_engine e{};
std::uniform_int_distribution<int> d{};
const int x{d(e)};
int arr[x]; // compiles
I can't tell if this is valid C++ or not. Clearly, the value of x
is not known until runtime. I think I may not understand the difference between C and C++ const
?