Find Related products on Amazon

Shop on Amazon

Implementing Generic Types in C

Published on: 2025-06-06 02:25:28

One of the most annoying things about programming in C is the lack of support for generic types, also known as parametric polymorphism. Not to be confused with the abomination that is _Generic. I wish C had something like the following: struct Vector { T* data; size_t capacity; size_t length; }; void vector_resize(Vector* v, size_t capacity) { v->data = realloc(v->data, capacity * sizeof(T)); v->capacity = capacity; } void vector_append(Vector* v, T element) { if (v->length >= v->capacity) { vector_resize(v, v->capacity ? v->capacity * 2 : 8); } v->data[v->length] = element; v->length++; } void vector_clear(Vector* v) { free(v->data); v->data = NULL; v->capacity = 0; v->length = 0; } Vector v = {0}; vector_resize(&v, 10); vector_push(&v, "abc"); vector_clean(&v); C++ can easily do the above with templates, and I personally quite enjoy programming in “C with methods, templates, namespaces and overloading”, avoiding the more complicated elements of C++ (lik ... Read full article.