Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty struct definitions illegal in C but not C++?

Tags:

c++

c

struct

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?

like image 585
Jason S Avatar asked May 17 '10 14:05

Jason S


People also ask

Can we define empty structure in C?

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.

Can we define empty structure?

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.

Can structs be empty?

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.

Why sizeof empty struct is 1?

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.


1 Answers

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.

like image 180
AnT Avatar answered Sep 22 '22 12:09

AnT