All Topics
All Topics
Technology
Technology
Design
Design
Programming
Programming
Science
Science
News
News
Gaming
Gaming
Entertainment
Entertainment
Business
Business
Finance
Finance
Sports
Sports
Health
Health
Food
Food
Travel
Travel
Art
Art
Music
Music
Books
Books
Education
Education
Politics
Politics
Personal
Personal
No algorithm. No AI slop. No ads. Just RSS. Pro-human. Indie writers. Real journalism. Open web. Chronological. Hand toasted.

Implementing Generic Programming in C: Techniques and Trade-offs

By

todsacerdoti

6mo ago· 7 min readen

Summary

The article explains how to implement generic programming in C despite the language not having built-in generics support. It covers various approaches including macros, void pointers, and type-specific macro generation, discussing the trade-offs of each method. The content focuses on practical implementation techniques for creating generic data structures like vectors in C, highlighting both the advantages and limitations of different approaches.

Key quotes

· 5 pulled
C is barebones and 'doesn't support' generics, but it's actually quite easy to implement with the tools we already have.
#define vector_push(vector, item) vector.buf[vector.idx++] = item; Con: This will cause everything to be inlined and loosely typed.
void vector_push(Vector vec, void *item); Con: You rely on type erasure to achieve generics, so you'll have to recast everything back to access them.
#define DECLARE_VECTOR(type) \ void vector_push(Vector##_
There's many ways you might find them being implemented in the wild. Some of the common ones are:
Snippet from the RSS feed
C is barebones and “doesn’t support” generics, but it’s actually quite easy to implement with the tools we already have. There’s many ways you might find them being implemented in the wild. Some of the common ones are:

You might also wanna read