Re: style: structures

Taylor R Campbell <[email protected]>
Newsgroups gmane.os.netbsd.devel.userlevel
Message-ID <[email protected]>
> Date: Tue, 8 Oct 2024 10:06:39 +0200
> From: [email protected]
> 
> In the style file, for structures, the emphasis is put on alignment in
> order to not waste memory because of undue padding.
> 
> Shouldn't an exception been mentionned concerning structures that may be
> derived from a base structure, so that the first member of the derived
> structures is a base structure, using the C standard guaranteed property
> that the address of the first member is the address of the structure,
> allowing to cast pointers in order to operate whether on the base
> structure or on the derived structure?

Don't do that.  Use container_of instead.

struct derived {
	struct base b;
	int x;
	...
};

int
foo(struct base *bptr)
{
	struct derived *dptr = container_of(bptr, struct derived, b);

	return dptr->x;
}

void
bar(struct derived *dptr)
{
	struct base *bptr = &dptr->b;

	mumble(bptr, &foo);
}

This way of writing things is independent of where the base structure
goes.  Of course, if there's layers of abstraction involved, it may
not be obvious -- and may not be stable across code evolution -- what
the optimally aligned member ordering is, so putting the base at the
beginning is fine.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.