Does ansi c support variable-length array?

I successfully compiled code like below.

#include<stdio.h>
#include<string.h>


int main()
{
    int co = 9;
    char a[co];
    strcpy(a, "hahahah");
    printf("co=%d\n", co);
    printf("a=%s\n", a);
    return 0;
}

gcc com.c -o com -ansi -Wall -O0

Yes. Variable Length Arrays is an ANSI C99 feature. But they are not supported under C++, neither under the previous C standard. Also, there is support for variable length arrays in many different compilers in the form of language extensions (like the GNU C extensions found in the GNU C compiler).

It complaints a little with '-pedantic' option.

Because '-pedantic' assumes that you're using ISO C90. In this previous standard, variable length array was forbidden.

If you want to use '-pedantic' , adds e.g. '-std=c99' to make sure you're checking against the ISO C99 standard.

/Lew

If you would like the compilation to fail -- perhaps because you need the code to conform to an older version of the C standard -- then you'd need to specify the c dialect with -std, specify that you'd like to be -pedantic, and turn warnings into errors.

For example, to strictly conform to c90 (synonymously c89) and reject any attempt to use a feature that is not part of that standard (such as a variable length array), gcc can be forced to abort compilation with a non-zero exit status with the following options:

gcc -std=c90 -pedantic -Werror ...

Regards,
Alister

I've had compilers not complain about variable-length arrays and still bungle them. Their dependence on them made the code quite difficult to repair, too. I wouldn't consider it a portable or reliable feature.

You can use malloc to reliably create almost any size array dynamically. This has been the standard approach forever.

thank you all.