From when did C start using variable length arrays?

Please tell me why the following code runs even on a strict C-99 compiler:

#include <stdio.h>
int main()
{
    int n;
    scanf("%d",&n);
    int a[n];
    a[1]=10;
    a[2]=5;
    printf("%d %d",a[1],a[2]);
}

The variable declaration must occur before any other statements in C right? If we so want a dynamically allocated array, we have to use memory allocation functions like malloc() but how come it is taking and input integer and allocating that sized array?

Answers


This is known as a variable-length array, and is supported by the C99 standard. This does not work in C89 or any version of C++.


In fact, there are two mechanisms in this code snippet that are not allowed in C90, but are in C99. The first is the variable size array declaration, using a[n]. The second is the mixing of declaration and code, with a being declared after a line of code.

I find this list by David Tribble handy. It is focused around C++ but gives you a good overview about the differences between C90 and C99 as well.

If we so want a dynamically allocated array, we have to use memory allocation functions like malloc()

Apparently you already know, but worth mentioning anyway: malloc() is used to allocate memory on the heap. The array in your example is allocated on the stack, which is a different mechanism. See this answer for an excellent explanation of the differences.


The feature is called variable length arrays, and to answer your question specifically, they were introduced in the C99 standard (probably some C compilers had them before, but any C99-compliant compiler must have them).

You'll find plenty of SO answers recommending you don't use them. With malloc(), there is a defined interface for memory allocation to fail: the call returns NULL. With VLA, there is no such interface: it's undefined behavior what happens when an allocation fails.


C99 allows for variable length arrays as in your example.

here is an artcile about it explaining more


Need Your Help