hn.today

Type Safe Generic Data Structures in C

danielchasehooper.com5 points0 comments
Screenshot of Type Safe Generic Data Structures in C

This explains a practical technique for writing type-safe, generic data structures in C by associating compile-time type information with a generic container using a union that carries a dummy payload of the element type. The write-up walks through simpler approaches - repeated-header macros, void* pointers, and inline storage with a flexible array member - showing their downsides (macro bloat, extra allocations and cache misses, manual size arguments) before presenting the union-based solution. With a List(type) union that contains both a generic internal node and a payload field, macros can use the ternary operator to force the compiler to check that an inserted item matches the payload type and automatically pass sizeof(payload) to allocation routines, eliminating memcpy-size arguments and giving real type errors when mismatched types are used.

Specifics include alternative implementations that use typeof() (now standardized in C23 and supported by mainstream compilers) to perform type-preserving casts for return values, and a casting-to-function-pointer trick (not strictly defined by the standard but practical) as another option. The union payload consumes no memory at runtime, and the approach generalizes to maps with multiple associated types. Caveats covered: alignment/size details for inline storage, older-compiler workarounds using the ternary trick instead of typeof, and the need for a typedef alias when passing identical-but-distinct List(type) definitions to functions. Example sources and a list_for macro are available by joining the author’s newsletter.

Read on danielchasehooper.com0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.