什么是不允许零长度阵列的基本原理或者sizeof == 0在C ++语言? [英] What is the rationale to disallow zero length arrays or sizeof == 0 in the C++ language?

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

问题描述

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

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

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

我知道一些编译器允许零长度数组作为延伸,并也是C99允许在一个结构,这是但更多的是可变长度数组中,并在结束时唯一可能的末尾零长度数组一个结构。

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,相比==,两个字符串可以是相等的,但它们可以是不同的弦,它们可以具有不同的身份)

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.

这篇关于什么是不允许零长度阵列的基本原理或者sizeof == 0在C ++语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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