有一些使用VLA(可变长度数组)的奇怪代码,由gcc 4.6被视为有效C(C99,C11):
$ cat a.c
int main(int argc,char**argv)
{
struct args_t{
int a;
int params[argc]; // << Wat?
// VLA in the middle of some struct, between other fields
int b;
} args;
args.b=0;
for(args.a=0;args.a
{
args.params[args.a]=argv[0][0];
args.b++;
}
return args.b;
}
这段代码编译没有警告:
$ gcc-4.6 -Wall -std=c99 a.c && echo $?
0
$ ./a.out ; echo $?
1
$ ./a.out 2; echo $?
2
$ ./a.out 2 3; echo $?
3
与-std = c1x相同:
$ gcc-4.6 -Wall -std=c1x a.c && echo $?
0
但是这不适用于Intel C Compiler或Clang LLVM:
$ icc a.c -o a.icc
a.c(5): warning #1361: variable-length array field type will be treated as zero-length array field type
int params[argc];
^
$ ./a.icc; echo $?
47
$ clang a.c -o a.clang
a.c:5:10: error: fields must have a constant size: 'variable length array in structure' extension will never be supported
int params[argc];
^
1 error generated.
所以:
>为什么这被GCC认为是有效的?
>如果它是GCC的扩展,它在哪里描述?
>是否在C99和C11 ISO标准中有效?