Why does C ++ allow variable-length arrays that are not dynamically allocated?

I am relatively new to C ++, and from the very beginning it was drilled into me that you cannot do something like

int x; cin >> x; int array[x]; 

Instead, you should use dynamic memory. However, I recently discovered that the above will be compiled (although I get an error message saying that this is prohibited by ISO C ++). I know that this is clearly a bad idea if it is not permitted by the standard, but I did not even know before that it was possible.

My question is, why does g ++ allow variable length arrays that are not dynamically allocated if it is prohibited by the standard? Also, if it is possible for the compiler, then why is this not a standard?

+7
c ++ dynamic-arrays
source share
4 answers

Support for variable length arrays (VLA) has been added to the C language in C99.

Probably since support for them exists in gcc (for C99 support), it was pretty simple to add support for them in g ++.

However, this is an implementation-specific language extension, and it is not recommended to use extensions for the implementation if you want your code to be portable.

+19
source share

Because it is supported on the C99. I can not say why this is not in the C ++ standard. However, it is not as useful as you might think, because it easily leads (if you are not careful) to a stack overflow (since it is usually based on alloca , which is non-standard in itself). Another mistake is to return a pointer to a dynamic array that immediately goes beyond.

+5
source share

Compiler lots cover and extend standards. There are two main reasons:

  • Unscrupulous compiler compilers probably think that making it harder to move away from their compiler helps to increase durability.
  • Benevolent compiler authors probably think that giving you more options when they can at the minimum cost to yourself is a good thing.
+3
source share

All the reasons that they are associated with them are correct, although there are limitations to this requirement. For example, you can demonstrate more flexible support than what is required in C (if you implemented this using scanf rather than cin, put it in a .c file and use gcc).

This is almost just an implicit call to alloca (allocate auto), which simply reduces the stack pointer (increases the size of the stack) and copies the new stack pointer to another register, which is used as a pointer to the allocated memory.

The difference is that constructors and destructors will not be called for objects created using alloca.

+1
source share

All Articles