A quick c++ array initialization question using non const variable


I am very new to C++ and I am wondering if I can do the following,

int a =5;
int b[a];

If so, what would happen if value of a changed? and any drawback using this.

If not,why it that?


I tried the same code on an online c++ compiler and it does work. but i just dont know if this is a standard practice or not. if not, what would be the standard practices of refering a dynamic value to initialize an array?

>Solution :

No you cannot do that. Array bounds in C++ must be constants. This is legal

const int a = 5; // a is a constant
int b[a];

Some compilers do allow your code, but it is an extension to the C++ language called a variable length array or VLA.

But even on the compilers that do allow it, nothing happens to b if you change a, it will still have the same size as when it was created.

You can avoid all these issues by using a vector, like this std::vector<int> b(a); That is the correct way to do what you are asking for. You need to #include <vector> for the std::vector class.

Leave a ReplyCancel reply