0

As I know in c++ if you want to crete an array, you must give constant value for its size. But here:

int main(){

    int a;
    cin >> a;
    int b[a] = {};

    for (int i = 0; i<a ; i++){
        b[i] = a;
        cout << b[i];
    }
    return 0;
}

If i input 5

output:

55555

It works fine in a way i can't understand in dev c++. If i run this in visual studio 2017, it gives error. Can anyone explanin why?

  • 2
    Variable Length Arrays are not standard C++ if you can use them then they are an extension of the compiler you are using. – Borgleader Oct 23 '18 at 15:33
  • Related: [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/q/1887097/2602718) – scohe001 Oct 23 '18 at 15:33

2 Answers2

0

As I know in c++ if you want to crete an array, you must give constant value for its size.

Correct. If you use a non-constant value, then the program is ill-formed. Yes, the program that you show is ill-formed.

It works fine in a way i can't understand ... Can anyone explanin why?

C++ compiler may allow compilation of an ill-formed program. This enables the compilers to extend the language. It appears that you were using a non-standard extension to C++.

This is what the GCC compiler says about your program:

warning: ISO C++ forbids variable length array 'b' [-Wvla]
int b[a] = {};
       ^
eerorika
  • 232,697
  • 12
  • 197
  • 326
0

Are you using GCC by any chance? This is a GCC extension and it's enable by default. In fact it's quite a dangerous one because it's fairly easy to cause a stack overflow on your program. It's roughly the same as using alloca().

In order to disable it, you should use a compiler flag called -Wpedantic. This will make your compiler issue a warning. (see this demonstration)

ISO C++ forbids variable length array ‘b’ [-Werror=vla]

Henrique Jung
  • 1,408
  • 1
  • 15
  • 23