为什么我被允许使用const修饰的变量在C数组的大小? [英] Why am I being allowed to use a const qualified variable as an array size in C?
问题描述
当我运行下面的code,它工作正常的C:
When I run the following code,it works fine for C:
#include<stdio.h>
int main(void)
{
const int x=5;
char arr[x];
printf("%d",sizeof(arr));
}
但是,并非只有我是常量前阅读
合格的变量不是真正
常数(这就是为什么他们能够吨开关的情况下
),但是从 IBM 证实了(<一个href=\"http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc03const_cv_qualifier.htm\"相对=nofollow> IBMLINK )说:情况
条件下使用
But not only had I read before that const
qualified variables are not real
constants (that's why they can't be used in case
condition of switch-case
),but the following link from IBM corroborates that (IBMLINK) and says:
const int k = 10;
int ary[k]; /* allowed in C++, not legal in C */
那么,为什么我是允许使用常量
限定变量在C作为一个数组的大小没有任何错误?
Why then am I allowed to use a const
qualified variable in C as an array size without any error?
推荐答案
C99
支持可变长度数组,但 C90
不支持变长数组,可以更清楚地看到这一点,如果您使用的是 GCC
,并尝试用这些参数来编译:
c99
support variable length arrays but c90
does not support variable length arrays, you can see this more clearly if you are using gcc
and try to compile with these arguments:
gcc -std=c89 -pedantic
这会给你以下警告:
warning: ISO C90 forbids variable length array ‘y’ [-Wvla]
但如果你编译使用 C99
这是完全没有问题:
gcc -std=c99 -pedantic
正如约翰·伯德作为2011年C标准变长数组中指出的( VLA
)现在是可选的。这里是一个布斯博士的VLA文章,也是一个链接 GCC
文档< /一>:由韦恩·康拉德指出。
As pointed out by John Bode as of the 2011 C standard variable length arrays(VLA
) are now optional. Here is a Dr Dobbs article on VLA and also a link to the gcc
docs as pointed out by Wayne Conrad.
这篇关于为什么我被允许使用const修饰的变量在C数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!