Reputation: 3
In C, when I declare an array of n
elements a[n]
, and n
is input by the user, it shouldn't work, because the array space will change from static memory to dynamic memory.
But it works! Why ?
Has the standard been updated or something?
Upvotes: 0
Views: 59
Reputation: 1079
The C99 standard allows for variable-length arrays, which is exactly the behaviour that your are describing.
Edit: C99 is not universally supported (at least by default). However, many compilers (such as GCC) have incorporated a subset of the C99 standard into their default compilation settings.
If you want to disable these features, you can do so in GCC by setting -ansi -pedantic
in your compilation settings. This ensures that anything not supported in ANSI C will generate errors.
Upvotes: 1
Reputation: 158529
Variable length arrays(VLA) are a C99 feature, so the compiler you are using supports VLA or is supporting it outside of C99 mode as an extension, such as gcc and clang.
the C++ standard on the other hand does not support VLAs but many compilers including the ones I listed above support VLA in C++ as an extension.
We can see they were added in C99 by going to the draft C99 standard in the Foreword
section it says:
[...]Major changes from the previous edition include:
and includes the following bullet:
— variable length arrays
Upvotes: 1
Reputation: 106092
But it works! Why ?
Because C99 introduced variable length arrays. and you can declare dynamic arrays.
If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.
Upvotes: 1