For the following code:
foo(int n){
int array[n];
}
I understand that this is invalid syntax and that it is invalid because the c++ sta
The one and only valid answer to your question is, because the standard says so.
In contrast to C99, C++ never bothered to specify variable length arrays (VLAs), so the only way to get variably sized arrays is using dynamic allocation, with malloc, new or some other memory-manager.
In fairness to C++, having runtime-sized stack-allocations slightly complicates stack-unwinding, which would also make exception-handling for the functions using the feature consequently more bothersome.
Anyway, even if your compiler provides that C99-feature as an extension, it's a good idea to always keep a really tight rein on your stack-usage:
There is no way to recover from blowing the stack-limit, and the error-case is simply left Undefined Behavior for a reason.
The easiest way to simulate VLAs in C++, though without the performance-benefit of avoiding dynamic allocation (and the danger of blowing the limit):
unique_ptr array{new T[n]};