what's the use of empty structs in C-style languages ?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Dec 3 03:13:45 UTC 2024


On Monday, December 2, 2024 10:03:22 AM MST Basile B. via Digitalmars-d-learn 
wrote:
> I've noticed that empty struct are always at least a size of 1,
> see [D explorer](https://godbolt.org/z/sGYcex4cf). There you can
> see `%example.S = type { [1 x i8] }`
>
> So te compiler inserts a dummy member so that that everything can
> work as usual.
>
> Big question is what is the problem if we specify that empty
> struct is an error ?

Sometimes, structs or classes are used to just group functions, and they
don't actually have any data. And there are probably other uses that I'm not
thinking of at the moment. Really though, I don't know why it's a problem
that they're a thing. They behave just like any other struct, and I've never
seen any problems caused by them.

Personally, I've used them in unit tests quite a bit when testing stuff that
doesn't need the structs to have actual data (e.g. because it was testing a
trait that was related to the functions on the struct). Making such structs
illegal would cause both druntime and Phobos to fail to compile for exactly
that reason. But it's certainly true that I haven't seen many cases where
using a struct with no members in an actual program made much sense.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list