Use a variable as the dimension of an array in C ++?
I'm just wondering why this works in Clang 4.0:
unsigned cnt = 42;
int k[cnt];
But it won't:
unsigned cnt = 42;
string bad[cnt];
I just checked out the C ++ primer 5th edition. It says that:
the size must be known at compile time, which means the dimension must be a constant expression
If so, why does it work int k[cnt];
?
+3
source to share
3 answers
None of the snippets work in C ++.
However, in C, you can use non-constant expressions as array sizes. Some compilers (like the GCC option without -pedantic
) support this C feature in C ++ code.
As for the difference between element types, it depends on the compiler. GCC compiles both. clang ++ disallows non-POD types (for example std::string
) in this case.
+14
source to share