I'm trying to declare a C++ variable that takes up zero bytes. Its in a union, and I started with the type as int[0]. I don't know if that is actually zero bytes (although sizeof(int[0]) was 0). I need a better way to declare a 0 byte type, and hopefully one that can be typedefed to something like nullType or emptyType. The variable is in a union, so in the end memory is reserved anyway. I tried void on the off chance it would work, but C++ complained. I'm using Ubuntu 10.10, with a current version of the kernel, and an up-to-date GCC. Here's the union:
union RandomArgumentTypesFirst
{
uint uintVal;
nullType nullVal;
}
And here is the typedef:
typedef int[0] nullType;
The compiler says this about the typedef:
error: variable or field ‘nullVal’ declared voidmake[2]:
When I typed in int[0]
, it worked. Any suggestions?
EDIT:
As @fefe said in the comments, the int[0]
may be provided as an extension by the compiler. GCC's website says that the compiler has many extensions by default.
A variable in C++ can never take zero bytes. Every object must have unique address, which is not possible if the size is zero.
By the way,
int[0]
is illegal in Standard C++. If you're using GCC, compile it with-pedantic
option, you will get this warning:Also, the syntax for
typedef
should be this:You cannot instantiate any data type in C++ that takes up zero bytes. The Standard dictates than an empty class, such as:
...will result in the following being true:
The reason for this is so that you can take the address of the object.
EDIT: I originally said the
sizeof
would be1
, but per @Als' comment, I have found the relevant passage in the Standard, and it is indeed simply non-zero:[Classes] §9/3
The standard explicitly prohibits the existence of an instance of a type with size 0, the reason is that if an object could have size 0, then two different objects could be located at the exact same address. An empty struct, for example, will be forced to have size > 0 to comply with that requirement even if when used as base of a different type, the compiler can have it have size == 0.
What is it that you want to do with an empty class?
The typedef is misspelled:
As others have pointed out, you cannot have an object of size 0; However, compilers can (and frequently do) provide the
Empty Base Class
optimization.It sounds like you want std::optional.
It won't have a
sizeof
0, but that's not important for expressing an empty value.On a related note, there is C++ proposal (P0146R1) to make
void
a regular type.The paper goes on to discuss why even
sizeof(void)
can't be 0.Although this question is targeted to C++, it should be noted that an empty struct in C may result in a
sizeof
of 0. This however, is undefined behavior.The C++ standard demands explicitly that every type have size at least 1. This is intimately tied to the requirement that each object have a unique address (consider
Foo x[10]
ifFoo
had size zero).