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
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).
source to share