3

While writing some code, I realised one of my code works which as per my understanding shouldn't be working. The code is

int main() {
    int val;
    cin>>val;
    int array[val];
}

No only this, even the code below is also working

 int main() {
        int valone = rand();
        int valtwo = rand();
        int array[valone][valtwo];
    }

I always had the understand that static arrays needs constant values, or the values which could be deduced by compilers during compile time.

Is there any change in recent C++11/14 specification or this was true for C++ since beginning.

NOTE: Visual Studio Compiler does gives an error in this case, but g++ as well as clang successfully compiles above code

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Daksh Gupta
  • 7,554
  • 2
  • 25
  • 36

5 Answers5

7

It's a variable-length array.

These are supported by C99, and both GCC and Clang support them in C++ as a non-standard extension. (They are not part of the C++ language.) MSVC does not support C99, and therefore does not support them at all.

In standard C++, you would use std::vector instead.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • to give it credit, MSVC 2015+ supports designated initializers, compound literals, and some other parts of C99 (not VLAs though), but only in C, not C++. – Cubbi Jan 18 '17 at 04:40
3

This is a compiler extension called Variable-Length Arrays. This is not standard C++ as you said and thus should not be relied on when trying to write cross-compiler compliant code. Instead, you can use std::vector for "dynamic arrays", this is standard.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
2

There are some compilers that allow variable-length arrays as an extension of the language. Don't rely on it if you want portable code, use std::vector instead.

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

Variable length arrays are not standard in c++. Some compilers support it, but as non-standard extensions.

For example, see thee gcc documentation for this extension here.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
0

VLA's are a very useful construct. They allow one to create an array of a size known at compile time, yet use automatic memory and not rely on dynamic memory management as vectors do.

There may be several reasons to avoid dynamic allocations, among most important would be performance penalty incurred by it (especially in multithreading scenarios) and simple lack of dynamic memory control on some MCUs.

SergeyA
  • 61,605
  • 5
  • 78
  • 137