I don't understand why this is an error because I have defined MAX as 10 right before int list[MAX]
You defined MAX
as 10 but you didn't define MAX
as constant. It's an error because the compiler insists that (in this case) the array bound must be an integer constant.
One way to fix the error is to make MAX
constant...
const int MAX = 10;
int list[MAX];
Another way to avoid the error is to move the array off the stack and onto the heap (since the bound of a heap array doesn't have to be constant) …
auto list = new int[MAX];
… however this changes the type of list
from int[10]
to int *
and also forces you to become responsible for managing the life of list by calling delete
when appropriate (which can be a non-trivial challenge) …
delete [] list;
Not deleting list
correctly can cause memory leaks.
You can avoid the error and avoid responsibility for managing the array by using a unique_ptr …
std::unique_ptr<int[]> list{ new int[MAX] };
However many well regarded authorities would argue that using a container like std::vector or std::array would be a better approach. For example, in Effective Modern C++ Scott Meyers says this...
The existence of std::unique_ptr for arrays should be of only intellectual interest to you, because std::array, std::vector, and std::string are virtually always better data structure choices than raw arrays. About the only situation I can conceive of when a std::unique_ptr would make sense would be when you’re using a C-like API that returns a raw pointer to a heap array that you assume ownership of.
At this point you may be wondering why MAX
has to be constant in your original code. I'm not a language lawyer but I believe the short answer is because the C++ Standard says it must be so.
For insight into why the standard imposes that requirement you could read some of the answers to the question Why aren't variable-length arrays part of the C++ standard?