15

I'm using MinGW to compile for C++11 and I found out that this doesn't throw an error:

int S;
cin>>S;
char array[S];

While this does ("storage size of 'array' isn't known"):

char array[];

To me, the size is also unknown in the first case, as it depends on what the user input is.

As far as I knew, automatic arrays are allocated at compile time in stack memory. So why wouldn't the first example fail?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Floella
  • 1,279
  • 1
  • 22
  • 41

3 Answers3

19

It's not. C++ doesn't have variable-length arrays, though some compilers allow it as an extension of the language.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
19

You are apparently not aware of the GNU GCC extension Arrays of Variable Length. Therefore your first code compiles.

The error message is something different. You have to specify the array length.

gcc has the -pedantic switch - enabling this switch the compiler will report your first code as invalid:

warning: ISO C++ forbids variable length array ‘array’

Read also this thread What is the purpose of using -pedantic in GCC/G++ compiler?

Use very carefully compiler extensions because should you port your code to another compiler then you are in big trouble.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Carsten
  • 325
  • 2
  • 12
3

[This answers the original version of the question which asked about a static array; Deduplicator corrected this misconception, but now the question is missing a part.]

If your assumption that this piece of code defined a static array were correct, you'd be wondering for a good reason indeed: Something that is determined at compile time, like data with static storage duration, can obviously not depend on user input at run time. This truism is independent of any specific language.

The array defined in your code snippet has, by contrast, automatic storage duration, vulgo is created on the stack. A complete minimal working example would have made the case clearer: It would have shown that the code is in a function.

Objects with automatic storage duration can be created as needed at run time; there is no logical problem preventing that, which should fix your general headache ;-).

But note that, as some programmer dude correctly remarked, standard C++ nevertheless does not permit the definition of arrays whose size is not known at compile time; standard C does though, since C99. The rationale for C++ no following that amendment is that C++ provides better means for the use case, like the vector template. gcc, which is the compiler used in MinGW, permits this as an extension (and why not — it's available in the compiler anyway).

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62