为什么我被允许在C中使用const限定变量作为数组大小?
当我运行以下代码时,它适用于C:
#include int main(void) { const int x=5; char arr[x]; printf("%d",sizeof(arr)); }
但是我不仅在之前读过const
限定变量不是real
常量(这就是为什么它们不能在switch-case
),但IBM的以下链接证实了( IBMLINK )并说:
const int k = 10; int ary[k]; /* allowed in C++, not legal in C */
为什么我允许在C中使用const
限定变量作为数组大小而没有任何错误?
c99
支持可变长度数组,但c90
不支持可变长度数组,如果你使用gcc
并尝试使用这些参数进行编译,你可以更清楚地看到它:
gcc -std=c89 -pedantic
这会给你以下警告:
warning: ISO C90 forbids variable length array 'y' [-Wvla]
但如果你使用c99
编译它是完全正常的:
gcc -std=c99 -pedantic
正如John Bode所指出的那样,2011 C标准可变长度数组( VLA
)现在是可选的。 这是关于VLA的Dr Dobbs文章,以及Wayne Conrad指出的gcc
文档的链接。