为什么允许我在 C 中使用 const 限定变量作为数组大小? [英] Why am I being allowed to use a const qualified variable as an array size in C?

查看:48
本文介绍了为什么允许我在 C 中使用 const 限定变量作为数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码时,它适用于 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));

}

但我之前不仅读过 const 限定变量不是 real 常量(这就是为什么它们不能用于 caseswitch-case 的条件),但来自 IBM 的以下链接证实了这一点(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 中使用 const 限定变量作为数组大小而没有任何错误?

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 编译它是完全没问题的:

but if you compile using c99 it is perfectly fine:

gcc -std=c99 -pedantic 

正如 John Bode 在 2011 年 C 标准中指出的那样,可变长度数组 (VLA) 现在是可选的.这是一篇关于 VLA 的 Dr Dobbs 文章,还有一篇链接到 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.

这篇关于为什么允许我在 C 中使用 const 限定变量作为数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆