Probably one of the basic questions… And answer is present in all the basic books. But a recent discussions motivated me to investigate a bit.
consider the following code snippet.
printf("size of empty is %d\n",sizeof(Empty);
So what will be the output? Many were quick to point out 1. Why? Because nothing can be zero? But interestingly this answer is NOT universal. It precisely depends on weather it is a C Program or a C++ Program. And the answer is correct only in case of C++ Program.
In C++ sizeof and empty struct/class will be one as nothing can be created of zero byte. Think what will be address of a variable of this type and How do I create an array of 100 Empty types? So C++ adds minimum allowable size (1 byte) to an Empty Struct.
But C Program it is different. gcc under linux reports the size to be 0. When some one first told me this I found it completely absurd as I failed to assign any logical explanation to this? I researched on and consulted latest c specification which suggests:
In C, an Empty struct is a constraint violation and should result in a compile time error. A struct with un-named entity will, however, have a non-standard size. Un-named membered struct?
:2; //an un-named 2 bit member
So Why gcc is reporting the size 0. Better ask them as it is a clear violation of well laid C language specification.
Why Size of Empty struct is 1 in C++ but not allowed in C?
An Interesting question; I must say. What differs between them? Let us first consider C (C has right to be considered first. Isn’t it). There is no logical reason in C to have a struct that doesn’t contain data? As it will serve no purpose; C doesn’t permit it.
So why it is permitted in C++? Simply because there are logical cases in C++ where you would like to create a struct/class without data. Think about utility class which are just function bundles (such as a Math Class, or implementation of a strategy pattern) or an abstract implementation or interface class.
In C++, we often need a class that may not have a data so in C++ an Empty struct is valid. Since it is valid is should have a valid size. In C, however, we never need an Empty struct so it is not permitted.