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.
  1. Panzerschrek

    I don't understand people reinventing macro-based hacks in C to achieve what was achieved in other languages many years ago. Why not using C++, for example? It's available almost everywhere, introducing its usage in an existing C codebase is pretty simple. Sure, C++ has its own downsides, but is it better to create mess with macros in C rather then using exiting language facilities and standard library containers provided by C++?

  2. lor_louis

    I wrote a summarizing article on type safe container types a while back, but

    with some C23 specific changes and a few tweaks to work better for complex types.

    https://louissven.xyz/article/how_I_do_container_types_in_C....

    Feel free to flag/delete if this isn't the place.

  3. tniemi

    That `(1 ? (item) : (list)->payload)` was a neat trick. It gets optimized away, but the type comparison happens before that.

    Still feels a bit like a party trick, but if it works...

  4. dang

    Related. Others?

    I write type-safe generic data structures in C - https://news.ycombinator.com/item?id=44425461 - June 2025 (182 comments)

    Type-safe generic data structures in C - https://news.ycombinator.com/item?id=26735655 - April 2021 (52 comments)

  5. add2

    While C++ template is using value types, C generic pointer is not.

  6. randomNumber7

    As far as I know many C programmers think the addition of variable length arrays in C99 was a mistake. What would be the downside of this approach?

  7. mkehrt

    I absolutely cannot remember the details, but we did typesafe, macro based generic data structures in C in an undergrad class I took ~20 years ago (CMU Operating Systems). The idea has definitely been around, though I don't know if the implantation was the same.

  8. veexx103

    Is it feasible to create a new language by adding features to C

    just as was done with C++?

More from this day

2026-10-05