Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thanks!

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading