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

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

问题描述

只是好奇,如果我在代码中定义一个零长度数组 int array[0]; 会发生什么?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.

这是因为我必须将一些代码发布到野外,所以我想弄清楚是否必须处理 SIZE 定义为 0,这发生在一些带有静态定义的 int array[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 没有抱怨,这导致了我的问题.从我收到的答案来看,我认为没有警告主要是由于支持尚未使用新 [] 语法更新的旧代码.

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.

因为我主要想知道错误,所以我将 Lundin 的答案标记为正确(Nawaz 是第一个,但它并不完整)——其他人指出它实际用于尾垫结构,同时相关, 不是我要找的.

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.

推荐答案

数组的大小不能为零.

ISO 9899:2011 6.7.6.2:

ISO 9899:2011 6.7.6.2:

如果表达式是一个常量表达式,它的值应该大于零.

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

以上文本对于普通数组(第 1 段)均适用.对于 VLA(可变长度数组),如果表达式的值小于或等于 0(第 5 段),则行为未定义.这是 C 标准中的规范性文本.不允许编译器以不同方式实现它.

The above text is true both for a plain array (paragraph 1). For a VLA (variable length array), the behavior is undefined if the expression's value is less than or equal to zero (paragraph 5). This is normative text in the C standard. A compiler is not allowed to implement it differently.

gcc -std=c99 -pedantic 对非 VLA 情况给出警告.

gcc -std=c99 -pedantic gives a warning for the non-VLA case.

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

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