struct t_empty {
};
This appears to compile properly in C++ but not C. (at least with the TI 28xx DSP compiler, where it emits the error "expected a declaration") Is this mentioned somewhere in the C standards, or is my compiler broken?
It's worth noting that empty structs are only somewhat supported in C and disallowed in C99. Empty structs are supported in C++ but different compilers implement them with varying results (for sizeof and struct offsets), especially once you start throwing inheritance into the mix. Save this answer.
It occupies zero bytes of storage. As the empty struct consumes zero bytes, it follows that it needs no padding. Thus a struct comprised of empty structs also consumes no storage.
An empty struct is a struct type without fields struct{} . The cool thing about an empty structure is that it occupies zero bytes of storage.
This is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class and structure must have a size of at least 1.
Empty struct is a syntax error in C. The grammar of C language is written so that it prohibits empty structs. I.e. you won't find it stated in the standard explicitly, it just follows from the grammar.
In C++ empty classes are indeed legal.
P.S. Note, that often you might see the quote from the C standard that says "If the struct-declaration-list contains no named members, the behavior is undefined.", which is presented as the portion of the document that prohibits empty structs. In reality, empty structs are, again, prohibited by the grammar. So a literally empty struct (as in your question) is a syntax error, not undefined behavior. The above quote from the standard applies to a different situation: a struct with no named members. A struct can end up non-empty, but at the same time with no named members if all members are unnamed bitfields
struct S {
int : 5;
};
In the above case the behavior is undefined. This is what the above quote is talking about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With