简体   繁体   中英

What is the rationale to disallow zero length arrays or sizeof == 0 in the C++ language?

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

struct x { };

but

sizeof(x) == 1

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.

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.

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

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)

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.

In my understanding, x[0] = has the same address with x. Therefore, the sizeof(x) always starts from 1, as x[0] is always initialized when you declare array x.

To answer your question, if we allowed zero length arrays in C, C++, the array would not actually be allocated at the point of definition. For example in Java, you declare an array

int [] a;

It is not allocated until you call

a = new int[10];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM