Get the latest tech news

I write type-safe generic data structures in C


I write type safe generic data structures in C using a technique that I haven’t seen elsewhere1. It involves unions and typeof, but we’ll get to that. My approach works for any type of data structure: maps, arrays, binary trees… but for this article I illustrate the ideas by implementing a basic linked list. Since many people aren’t aware you can do C generics at all, I figured I’d start simple and build up to this:

My approach works for any type of data structure: maps, arrays, binary trees… but for this article I illustrate the ideas by implementing a basic linked list. While Clang and gcc have supported it for a long time, some compilers haven’t (like msvc versions prior to 19.39). Thanks to Martin Fouilleul for the encouragement to finish this post, which I’ve been sitting on for months, and the feedback on early drafts.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of type

type

Related news:

News photo

10 out of 12 people cured in Type 1 Diabetes Study

News photo

Type-based vs. Value-based Reflection

News photo

Get a custom paint job for earbuds at a nail salon, type on a baguette, then build a fountain for your PC