The C/C++ language requires that stack-based arrays have sizes known at compile time.
In the first case, because i is not a constant, line 2 violates this rule. Note that some
compilers -- namely gcc -- do allow this as an extension to the language.
In the second case, the array is heap-based. Variable length array allocations have to
be supported by the language otherwise the language is useless.
The third case AFAIK should compile since i is constant.
The third one indeed compiles, as does the first one using gcc. (I dont have any other compiler at the moment... so couldnt test...).
But what should a beginner do to avoid differences between compilers?
A person learning using gcc will always beleive that it is not necessary to have a constant size for array declaration.
I believe it is valid in C99 but maybe not in C++?
In C++ and pre-C99 versions of C, an array's size must be a constant integral expression so that it can be calculated at compile-time. In C99, this restriction was relaxed. An array's size must be an integral expression, not necessarily a constant one. This allows you to declare a variable-length array or an array whose size is determined at runtime. For example:
There is no problem; obviously gcc got it to work.
The issue is that the compiler likes to know what the offsets are of each local variable in the current stack frame
at compile time. Variable length arrays make that impossible ... the compiler now has to generate code to compute
some of the offsets, which means it must also store the actual length of the array on the stack at a known location.
EDIT: Or, to make a long story short, it makes accessing (some) local variables a wee bit slower.