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

前端之家收集整理的这篇文章主要介绍了在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.

原文链接:https://www.f2er.com/c/112887.html

猜你在找的C&C++相关文章