Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can there be a C++ type that takes 0 bytes

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.

like image 536
Linuxios Avatar asked Nov 25 '11 16:11

Linuxios


People also ask

Can a file have 0 bytes?

A zero-byte file is a file that does not contain any data. While most files contain several bytes, kilobytes (thousands of bytes) or megabytes (millions of bytes) of information, the aptly-named zero-byte file contains zero bytes. Usually a file will contain at least a few bytes.

Why is my PDF 0 bytes?

As the PDF shows as "0" bytes, it means the file is empty. It seems that the file has been damaged. Sorry to say it is not possible to recover the file once it is damaged. Please check if you have saved the copy of that file to some other location.


Video Answer


2 Answers

You cannot instantiate any data type in C++ that takes up zero bytes. The Standard dictates than an empty class, such as:

class Empty {};

...will result in the following being true:

Empty emp;
assert( sizeof(emp) != 0 );

The reason for this is so that you can take the address of the object.

EDIT: I originally said the sizeof would be 1, but per @Als' comment, I have found the relevant passage in the Standard, and it is indeed simply non-zero:

[Classes] §9/3

Complete objects and member subobjects of class type shall have nonzero size

like image 97
John Dibling Avatar answered Sep 30 '22 02:09

John Dibling


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?

like image 33
David Rodríguez - dribeas Avatar answered Sep 30 '22 04:09

David Rodríguez - dribeas