3

I was just wondering why this works in Clang 4.0:

unsigned cnt = 42;
int k[cnt];

But this won't:

unsigned cnt = 42;
string bad[cnt];

I just checked C++ primer 5th edition. It says that:

the dimension must be known at compile time, which means that the dimension must be a constant expression

If that's true, why does the int k[cnt]; work?

Rich
  • 5,603
  • 9
  • 39
  • 61
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237

3 Answers3

14

Neither snippet works in C++.

However, in C, it's possible to use non-constant expressions as array sizes. Some compilers (for example, GCC without -pedantic option) support that C feature in C++ code.

As for the difference between element types, it's compiler-specific. GCC compiles both. clang++ prohibits non-POD types (such as std::string) in this case.

Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • C++11 does not support it. However, the feature is planned for C++14 or C++17. With some restrictions compared to C99/C11 though. – Morwenn Feb 10 '13 at 13:56
  • 1
    @Morwenn it's being considered (after all, it is existing practice for many C++ implementations), Stroustup is for it, as long as pointer type can be fixed (in C, pointer to an element of VLA is not compatible with pointer to an element of a regular array) – Cubbi Feb 10 '13 at 14:12
  • Yes. And they also consider not to port the run-time behaviour of `sizeof` if I'm not wrong. – Morwenn Feb 10 '13 at 20:14
0

What compiler are you using, I am using gcc and both const and nonconst works fine.

It is not a matter of c, arrays are not meant to be defined through variables, only macros and const expressions.

It's a matter of compiler's interpretation, I doubt it is related to standards.

Dmytro
  • 5,068
  • 4
  • 39
  • 50
0

Is clang 4.0 actually apple xcode clang? i think that is actually version 3.1. clang offers a nice explanation itself:

warning: variable length arrays are a C99 feature
      [-Wvla-extension]
    int k[cnt];
Martin Wirth
  • 153
  • 1
  • 6