What are the benefits of unnamed structs / unions in C?

The benefit is pretty obvious, isn't it? It saves the programmer from coming up with a name! Since naming things is hard, it's nice that it's possible to avoid doing so if there is no real need.

It's also a pretty clear signal that this struct is local and never used anywhere else but in the context of being a field in the parent struct, which is really, really nice information since it reduces the possibility of needless coupling.

Think of it as static; it restricts the visibility of the inner struct to the outer one, in a manner similar to (but not, of course, equivalent with) how static restricts the visibility of global symbols to the compilation unit in which they appear.


It does not have to be an anonymous struct inside a struct, which I do not find very useful: this will typically only change the layout slightly by introducing more padding, with no other visible effects (compared to inlining the members of the child struct into the parent struct).

I think that the advantage of anonymous struct/unions is elsewhere: they can be used to place an anonymous struct inside an union or an anonymous union inside a struct.

Example:

union u
{
  int i;
  struct { char b1; char b2; char b3; char b4; };
};

Tags:

C

Struct

Unions