Tuesday, March 11, 2008

Size of an empty struct

Size of Empty struct

When I was teaching, some students used to ask me a question. Why is size of an empty struct 1 in C++ and 0 in C ? I coded and found out that gnu compiler does give this result whereas other compilers like tc and vc++ give an error for empty structure in c ? What is the reason?
#include
struct emptystr
{
};
int main()
{
printf(“%d”,sizeof(struct emptystr));
}

Compile it under gcc. The answer is 0 and under g++ answer is 1.
It can be explained like this . Let us say an empty struct has a size of zero. Then two adjacent variables of this structure type must have the same address. Address of any variable must be unique. Hence it is not possible to have size of any variable or data type as zero.
Then how do you explain the fact that in C, size is 0. The actual reason is, according to ANSI standard, sizeof operator can not be applied to incomplete data types. An empty structure is incomplete. Hence 0 we are getting is garbage. Try to compile this program with flag –pedantic-errors. You will get a syntax error.

gcc emptystr.c –pedantic-erros

You will get an error which says struct has no members.

Then how is empty structure valid in C++ ? C++ being OOP language, a structure can contain methods as well as data members. Even though the structure has no data members, there are at least a constructor and destructor which are supplied by compiler.
Hence the type is not incomplete. (well it is in fact similar to a structure or class with only function members )

struct onlyfuntcions{
void print()
{
Cout<<”Hello”;
}
};
Size of this structure in c++ is also 1 byte.
Now don’t get scared. You did not know that a struct can also have constructor?? It can have. Struct in C++ is very much similar to class. The only difference between the two is struct members by default are public where as class members by default are private.

No comments: