A Trick for Type-Safe Generic Data Structures in C

Type Safe Generic Data Structures in C

A Trick for Type-Safe Generic Data Structures in C

Daniel Chase Hooper shows how to make generic data structures in C type-safe using a union with a payload member. The compiler catches type mismatches when you pass the wrong type to a macro like list_prepend, and the payload member takes no memory. He also covers inline storage with flexible array members and using __typeof__ for type-safe returns.

The way I found to do this is to use a union with a payload member that has a parameterized type.

More from this day

2026-10-05