在C89中的数组声明中使用sizeof()

我的印象是C89中不可能有变量大小的数组声明.但是,当使用clang -ansi编译时,我可以运行以下代码
double array[] = { 0.0,1.0,2.0,3.0,4.0 };
double other_array[sizeof(array)] = { 0.0 };

这里发生了什么?这不是一个可变大小的数组声明吗?

解决方法

那是因为sizeof运算符的结果是常量表达式,所以它不符合VLA的条件,就像下面的声明一样:
int other_array[5];

也不能是可变长度数组.来自C11(N1570)§6.6/ p6常数表达(强调我的未来):

An integer constant expression117) shall have integer type and shall
only have operands that are integer constants,enumeration constants,
character constants,sizeof expressions whose results are integer
constants
,_Alignof expressions,and floating constants that are the
immediate operands of casts.

为了完整起见,运算符的大小并不总是导致恒定表达式,尽管这仅影响C89后的标准(在C11的VLA中是可选的).参考§6.5.3.4/ p2 sizeof和_Alignof运算符:

If the type of the operand is a variable length array type,the
operand is evaluated; otherwise,the operand is not evaluated and the
result is an integer constant.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...