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
?
You are correct VLAs are a C99 feature(optional in C11) and the C++ standard does not include this feature although both
gcc
andclang
allow them in C++ as an extension. We can see they are not allowed by going to the draft C++11 standard section8.3.4
Arrays which says:For both
gcc
andclang
using the-pedantic
flag will warn when you are using an extension. If you are targeting C++11 then you should also specify that using-std=c++11
. You can use-pedantic-errors
to turn the warning into errors. If you compile your code using-pedantic
you should see the the following warning:gcc
documents their support for various standards, defaults and flags to enforce standard on their Language Standards Supported by GCC page and it says:In general
clang
supports whatgcc
does but you can find more details on their Language Compatibility page.Note as mentioned by GingerPlusPlus std:vector is considered the alternative for VLA in C++.