0

I am reading C++ Primer plus on arrays, and it says the following

typeName arrayName[arraySize]; 
//Arraysize cannot be a variable whose value is set while the program is running"

However, I wrote a program

#include <iostream>

using namespace std;    

int main()
{
    int n;
    cin>>n;

    int array[n];

    for(int i=0; i<n; i++)
    {
        cout<<array[i]<<endl;
    }
}

And it works fine, I am able to set the size of the array during run time. I am not getting any compilation errors, or run time crashes.

Can someone explain what is happening?

Thanks

Telenoobies
  • 938
  • 3
  • 16
  • 33

1 Answers1

7

Some compilers like g++ allow the use of C variable length arrays and will happily compile the code without any warnings or error. This is not standard and is a compiler extension.

If you need an "array" and you do not know what the size will be until run time then I suggest you use a std::vector You can use it as a direct replacement to an array but it allows run time sizing and it offers a lot of other useful features.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • This is no longer just a compiler extension but part of the C99 standard which allows variable sized arrays on the stack. (see also https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html) – Florian May 02 '16 at 16:48
  • 2
    @Florian C++ does not include all of C99. VLA's are not standard in any version of C++ – NathanOliver May 02 '16 at 16:49
  • wow that surprises me, but you are right. But actually, if you need a VLA in C++, you'd use a vector<> anyway, wouldn't wou? – Florian May 02 '16 at 16:53
  • @Florian Yes, which is what I say in my answer. – NathanOliver May 02 '16 at 16:54
  • 1
    @Florian It really should not surprise you. C and C++ are two different languages. There share a common set of behavior and many a C program can be compiled as C++ but they are different. – NathanOliver May 02 '16 at 16:56
  • Absolutely, you are right, i didn't want to dispute... It's just a valid explanation why they didn't take this C99 feature into C++ although it had even been proposed for TR2. BTW: do you know a good overview of features contained in C99 but not in C++? – Florian May 02 '16 at 16:59
  • @Florian I am not sure where a good resource like that is. – NathanOliver May 02 '16 at 17:09