I love C so much, and I really want to hate sepples, but I can't help but think that generic programming in C is shit! Macros are no good for generic data structures, as they are clunky and blow out code size, nor are void pointers, as you need to allocate separate memory just to store an integer (don't stuff ints into pointers; zeros won't work on architectures where the null pointer constant is non-zero). I really want to write my data structure library in sepples, where templates allow type genericism without issue. What should I do, /prague/; what should I do?!
Name:
Anonymous2012-01-14 6:56
A generic linked list that will contain anything you could think of. No macros! It assumes struct node has the strictest alignment.
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
// API
struct list;
struct list *make_list(size_t elem_size);
void *prepend(struct list *l);
void *append(struct list *l);
void *insert_after(struct list *l, void *node);
void *insert_before(struct list *l, void *node);
void *head(struct list *l);
void *tail(struct list *l);
void *next(void *node);
void *previous(void *node);
// implementation
struct list
{
size_t elem_size;
struct node head, tail;
};
struct node
{
struct node *prev, *next;
};
struct list *make_list(size_t elem_size)
{
struct list *l;
for (p = next(head(l)); p != tail(l); p = next(p)) {
printf("%s %d\n", p->name, p->age);
}
exit(EXIT_SUCCESS);
}
I wrote this on my phone, so I probably made some mistakes. I didn't bother to add remove() or error handling, but that should be straight-forward.