⌈LUNAR GARDEN⌋

toddgaunt@protonmail.ch

Generic Vectors in C

2018-02-22

Creating generic types and procedures in C is generally done two ways: With code generation (cpp, m4) or void *. The second method, void * has the benefit of only having to compile once, but it throws type-safety out the window. Worse, however, is that for something like a vector it can only store pointer-sized elements in the vector, which causes extra indirection when trying to store a vector of elements larger than pointers.

I decided to write generic vector using cpp macros that uses some C11 syntax tricks to create a very C++ esque vector type that fits inside a single C header file, and is only 60 lines of code.

Example

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "vec.h"

typedef Vec(char) Vecchar;

int
main()
{
        int x;

        Vec(int) vector = VEC_INIT;
        VEC_RESERVE(&vector, 20);
        VEC_PUSH(&vector, 5);
        x = *VEC_GET(&vector, 0);
        printf("%d\n", x);
}
-Todd Gaunt
• return •