The article presents a novel method to create type-safe generic data structures in C by leveraging unions to carry compile-time type information without runtime overhead.
It describes four levels of generic implementation: macro-based headers, void pointers, inline flexible array storage, and union-based type checking.
The union-based technique defines List(type) and uses a dummy payload member for type inference, letting the compiler enforce correct data types.
The list_prepend macro casts the internal function pointer to enforce type safety, automatically supplies the correct size, and triggers compile errors on mismatched types.
This approach extends to other data structures like maps and can support older compilers by using typedefs and struct-based unions for compatibility.
Get notified when new stories are published for "🇺🇸 Hacker News English"