Now, people have already stated that int a[n]
is not valid c++. But Perhaps I could help you with the answer you're looking for.
What is the advantage of dynamic arrays in this case then?
The syntax int a[n]
is called a VLA (Variable Length Array). These are illegal in C++ but allowed in C. So let's focus on the technical differences, or rather disadvantages of VLAs.
Let's get the obvious thing out of the way first. C89 and before did not have VLA and hence dynamic allocation was the only way for allocating variable length memory.
One more thing, static arrays and even VLAs are allocated on the stack (although this is implementation defined, but more often than not, it will be on the stack). Whereas dynamic arrays are allocated on the heap. For more information on the stack and the heap, read this
Now, VLAs are banned in C++ for a very good reason. VLAs can cause all sorts of undefined behaviours and should always be avoided unless you know exactly what you're doing. And by "you know exactly what you're doing", I mean you know that the size argument of that VLA will not overflow the stack.
Suppose VLAs were allowed in C++, this line in your code-
cin>>n;
int a[n];
What if the user enters a massive n
, way more than the stack size? That's a guaranteed stack overflow. Notice the problem? As compared to the heap, the stack is very tiny. This is also explained here and also here
And this is the primary reason VLAs should be avoided at all costs. Though VLAs actually come with much more boom than the aforementioned. Infact I always keep a list of UBs associated with VLAs handy, there just is that many problems.
So going back to my point of
[VLAs] should always be avoided unless you know exactly what you're doing
Honestly, you should never use VLAs, and you really can't because that's not even standard C++. But stack allocation is often faster than heap allocation. Though not for reasons one might consider obvious. Read this. So sometimes, if you're on C (not C++), the only times using a VLA is safe is when you know the max size of n
in int a[n]
will not overflow the stack and the declaration of the VLA is at the top of the scope you are currently declaring it at. The creator of alloca
(which used to be the only way to use VLA prior to c99) seems to agree.
Excerpt from here-
You may use alloca() in the form of:
pointer_variable = alloca(expression);
as an expression statement in the outermost block of a function.
Oh and just to answer your edit:
Thanks for your answers. Some users responded by saying that declaring an array by typing a[n] is not allowed. However, why does my program run fine when I type the following code :
It's because your compiler allows it. But remember, the standard does not. So these kinds of things can give birth to the good ol' "It worked on my machine!"