Why can't you use a variable to size an array in C ++?

According to my C ++ tutorial, the following expression:

cout << "Enter number of students\n";
cin >> number;
int score [number];


Is an ILLEGAL expression . I cannot use a variable for the size of the array.

Why can't I do this? (I am not looking for alternatives, I missed pointers, vectors, etc., but I want to understand this behavior.)


source to share

2 answers

Variable length arrays were not supported in ISO C90 / ANSI C89, from which C ++ is derived. While VLAs were added in C99, which is different from C ++, they may not be needed in C ++, which has STL container classes to provide more flexible methods for storing multiple objects.



In C ++, the compiler needs to know the amount of memory to allocate for an array at compile time. However, the value of the variable is unknown until run time. This is why you are not allowed to use a variable for the size of the array.

If you need to use arrays for your class project, I suggest using them const

to determine the maximum size you allow. You will later learn how to use other methods such as pointers and STL containers (like std :: vector).



All Articles