Implementing Generic Programming in C: Techniques and Trade-offs
By
todsacerdoti
Slow-proofed and worth the wait. Worth its weight in flour.
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 pulledC 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:
You might also wanna read
Cscript Style Guide: A Python-Inspired Approach to C Programming
Cscript is presented as a style guide for writing C code that aims to make C development faster and more Python-like while maintaining C's p
Pigeon's Device: An Independent Loop Optimization Technique in C Programming
The article introduces Pigeon's device, a loop optimization technique in C programming that was independently developed from Duff's device.
Implementing Closures in C Using JIT-Compiled Wrappers for Win32 Window Procedures
The article discusses an advanced programming technique for creating closures in C using JIT-compiled wrappers, specifically applied to Win3
Guidelines for Writing Fully Encapsulated C Programs: Pure vs Performance Approaches
This article presents a comprehensive set of rules and guidelines for writing fully encapsulated C programs, developed by the author over ye
Checked-size Array Parameters in C: Addressing Safety Issues with Array Size Validation
The article discusses a recent attempt to add safety checks for array parameters in the C programming language, specifically within the cryp
Creating a Leak-Free, Thread-Safe Grep Utility in C23 with Safe Programming Practices
The article details the author's experience creating a leak-free, thread-safe grep utility in C23 using a custom header file called safe_c.h
