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. Ie, 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
and clang
allow them in C++ as an extension. We can see they are not allowed by going to the draft C++11 standard section 8.3.4
Arrays which says:
D1 [ constant-expressionopt] attribute-specifier-seqopt
^^^^^^^^^^^^^^^^^^^^^^
For both gcc
and clang
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:
warning: ISO C++ forbids variable length array 'arr' [-Wvla]
int arr[x]; // compiles
^
gcc
documents their support for various standards, defaults and flags to enforce standard on their Language Standards Supported by GCC page and it says:
to obtain all the diagnostics required by the standard, you should also specify -pedantic (or -pedantic-errors if you want them to be errors rather than warnings).
In general clang
supports what gcc
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++.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.