Why am I being allowed to use a const qualified variable as an array size in C?

馋奶兔 提交于 2019-11-26 06:49:32

问题


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));

}

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 */

Why then am I allowed to use a const qualified variable in C as an array size without any error?


回答1:


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

this will give you the following warning:

warning: ISO C90 forbids variable length array ‘y’ [-Wvla]

but if you compile using c99 it is perfectly fine:

gcc -std=c99 -pedantic 

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.



来源:https://stackoverflow.com/questions/16588265/why-am-i-being-allowed-to-use-a-const-qualified-variable-as-an-array-size-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!