如果我定义C / C ++一个0大小的数组,会发生什么? [英] What happens if I define a 0-size array in C/C++?

查看:165
本文介绍了如果我定义C / C ++一个0大小的数组,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是好奇,如果我定义了一个长度为零的数组实际上发生了什么 int数组[0]; 在code? GCC不出现任​​何提示。

Just curious, what actually happens if I define a zero-length array int array[0]; in code? GCC doesn't complain at all.

示例程序

#include <stdio.h>

int main() {
    int arr[0];
    return 0;
}

澄清

实际上,我想弄清楚,如果零长度数组初始化这种方式,而不是被指着像Darhazer的言论变长,优化了还是不行。

I'm actually trying to figure out if zero-length arrays initialised this way, instead of being pointed at like the variable length in Darhazer's comments, are optimised out or not.

这是因为我必须释放一些code OUT到野外,所以我想弄清楚,如果我要处理的情况下尺寸被定义为 0 ,它发生在一些code。与静态定义的 int数组[SIZE];

This is because I have to release some code out into the wild, so I'm trying to figure out if I have to handle cases where the SIZE is defined as 0, which happens in some code with a statically defined int array[SIZE];

实际上,我是惊讶,GCC不抱怨,这导致了我的问题。从我收到的答案,我相信没有一个警告主要是由于支持老code还没有被更新,新的[]语法。

I was actually surprised that GCC does not complain, which led to my question. From the answers I've received, I believe the lack of a warning is largely due to supporting old code which has not been updated with the new [] syntax.

由于我主要是想了解一下错误,我标记伦丁的答案正确(谢里夫的是第一个,但它并不完整) - 其他的人指明了尾填充结构,它的实际使用,而有关,不正是我一直在寻找。

Because I was mainly wondering about the error, I am tagging Lundin's answer as correct (Nawaz's was first, but it wasn't as complete) -- the others were pointing out its actual use for tail-padded structures, while relevant, isn't exactly what I was looking for.

推荐答案

这是数组不能有大小为零。

An array cannot have zero size.

ISO 9899:2011 6.7.6.2:

ISO 9899:2011 6.7.6.2:

如果除权pression是一个不断前pression,应当有一个值大于零。

If the expression is a constant expression, it shall have a value greater than zero.

以上文字既是一个普通数组为真(§1)和VLA(§5)。这是C标准的规范文本。编译器是不允许不同的方式实现它。

The above text is true both for a plain array (§1) and a VLA (§5). This is normative text in the C standard. A compiler is not allowed to implement it differently.

GCC -std = C99 -pedantic发出警告这一点。

gcc -std=c99 -pedantic gives a warning for this.

这篇关于如果我定义C / C ++一个0大小的数组,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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