在C ++语言中禁止零长度数组或sizeof == 0的原因是什么? [英] What is the rationale to disallow zero length arrays or sizeof == 0 in the C++ language?

查看:357
本文介绍了在C ++语言中禁止零长度数组或sizeof == 0的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准要求所有类型的大小至少为1个字节,即使结构没有成员。即

The C++ standard requires that all types are at least 1 byte in size even though a struct has no members. i.e.

struct x { };

sizeof(x) == 1

它不是标准符合声明零长度数组(在C,C ++和C99)。

Same is with arrays. It is not standard conforming to declare zero length arrays (in C, C++ and C99).

int x[0];   // not allowed in C, C++ and C99 standards

那么为什么呢?对我来说,这似乎是一个不必要的要求,实际上引入了不一致。

So why is that? To me it seems like an uneccessary requirement, that actually introduces inconsistency.

我知道一些编译器允许零长度数组作为扩展,并且C99允许一个零length数组在结构的末尾,但是更多的是可变长度数组,只能在结构的末尾。

I know that some compilers allow zero length arrays as an extention, and also that C99 allows a "zero" length array at the end of a structure, which is however more of a variable length array and only possible at the end of a struct.

所以我的问题是:是fobidding零长度数组或在语言标准中要求sizeof> 0的基本原理?

So my question is: what is the rationale behind fobidding zero length arrays or requiring sizeof > 0 in the language standards?

推荐答案

如果某个大小大于等于1,则没有两个事物可以具有相同的地址,的事情是它的身份。 (像Python中的is,与==相比,两个字符串可以相等,但它们可能是不同的字符串,它们可能有不同的身份)

If something has a size >= 1, then no two "things" can have the same address, and thus the address of a thing is it's identity. (like "is" in Python, compared to ==, two strings can be equal but they may be different strings, they may have different identities)

(回到C,这是在语言变得如此正式之前创建的功能性),它使指针算术有意义,停止奇怪的内存分配,允许指针被比较检查身份....零将是一个恼人的特殊

I can also imagine (going back to C, which was created with functionality in mind before languages became so formal) that it makes pointer arithmetic make sense, stops weird memory allocations, allows pointers to be compared to check identity.... zero would be an annoying special case.

这篇关于在C ++语言中禁止零长度数组或sizeof == 0的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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