According to me, it is zero but there seems to be bit confusion here
I have tested it with gcc compiler and it gives me zero as output. I know that in C++, size of an empty class is 1. Let me know if I am missing anything here.
According to me, it is zero but there seems to be bit confusion here
I have tested it with gcc compiler and it gives me zero as output. I know that in C++, size of an empty class is 1. Let me know if I am missing anything here.
A struct cannot be empty in C because the syntax forbids it. Furthermore, there is a semantic constraint that makes behavior undefined if a struct has no named member:
struct-or-union-specifier:
struct-or-union identifieropt { struct-declaration-list }
struct-or-union identifier
struct-or-union:
struct
union
struct-declaration-list:
struct-declaration
struct-declaration-list struct-declaration
struct-declaration:
specifier-qualifier-list struct-declarator-list ;
/* type-specifier or qualifier required here! */
specifier-qualifier-list:
type-specifier specifier-qualifier-listopt
type-qualifier specifier-qualifier-listopt
struct-declarator-list:
struct-declarator
struct-declarator-list , struct-declarator
struct-declarator:
declarator
declaratoropt : constant-expression
If you write
struct identifier { };
It will give you a diagnostic message, because you violate syntactic rules. If you write
struct identifier { int : 0; };
Then you have a non-empty struct with no named members, thus making behavior undefined, and not requiring a diagnostic:
If the struct-declaration-list contains no named members, the behavior is undefined.
Notice that the following is disallowed because a flexible array member cannot be the first member:
struct identifier { type ident[]; };
In C99: "If the struct-declaration-list contains no named members, the behavior is undefined."
The syntax doesn't really allow it anyway, though I don't see anything that says a diagnostic is required, which puts it pretty much back in the "undefined behavior" camp.
The C grammar doesn't allow the contents of a struct
to be empty - there has to be at least an unnamed bitfield or a named member (as far as the grammar is concerned - I'm not sure if a struct that contains only an unnamed bitfield is otherwise valid).
Support for empty structs in C are an extension in GCC.
In C++ and empty struct/class member-specification is explicitly permitted, but the size is defined to be 1 - unless as part of the empty base optimization the compiler is allowed to make an empty base class take no space in the derived class.