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


Whichever compiler you are using, I am using gcc and both const and nonconst work great.

It's not a question of c, arrays are not meant to be defined via variables, only macros and const expressions.



This is a matter of compiler interpretation, I doubt it is related to standards.

0


source


Is clang 4.0 actually apple's xcode clang? i think this is actually version 3.1. clang offers a good explanation:

warning: variable length arrays are a C99 feature
      [-Wvla-extension]
    int k[cnt];

      

0


source







All Articles