tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: style: structures



> Date: Tue, 8 Oct 2024 10:06:39 +0200
> From: tlaronde%kergis.com@localhost
> 
> 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.


Home | Main Index | Thread Index | Old Index