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

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

This is no longer just a compiler extension but part of the C99 standard which allows variable sized arrays on the stack. (see also gcc.gnu.org/onlinedocs/gcc/Variable-Length.html)
@Florian C++ does not include all of C99. VLA's are not standard in any version of C++
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 Yes, which is what I say in my answer.
@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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.