It's not only that C doesn't have closures; it doesn't even have anonymous functions. Here's a little Lisp expression that doesn't need closures
(mapcar #'(lambda (x) (* x x)) some-list)
which squares all the elements of the list. To do that in C you need some abomination like /* Somewhere outside the function where you actually need this */
int square(x) { return x*x; }
/* ... */
List *r = List_new();
LIST_FOREACH(self, i, v, List_append_(r, square(v)););
Not to mention that this sort of thing tends to get ugly without automatic memory management.It's not necessarily just ugly but plain idiomatic C. It's just C: a function pointer + userdata pointer.
All hooks, callbacks, etc. use this approach because that's what a closure is on a low enough level. And in C it looks like void()(void userdata).
Re:List Processing in C
by timrobinson on Tuesday December 21, 2010 @06:23AM
(#2027515)
My "ugly" comment comes from spending my career programming against APIs like this :)
typedef BOOL (* WNDENUMPROC) (HWND, LPARAM);
BOOL WINAPI EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);
Re:List Processing in C
by JoachimSchipper on Tuesday December 21, 2010 @06:46AM
(#2027545)
The proper way to do this is (simplified from BSD sys/queue.h):
#define LIST_FOREACH(var, head) \
for ((var) = (head); (var) != NULL; (var) = (var)->next);
LIST_FOREACH(list_p, list_head) {
...
}
You may also occasionally want to use (C99) variadic macros (gcc seems to need -std=c99): #define LIST_MAP(my_list, f, ...) \
for (struct list *n = my_list; n != NULL; n = n->next) \
f(__VA_ARGS__, n)
void list_print(const char *format, struct list *n) {
printf(format, n->data);
}
int main(void) {
struct list n3 = {NULL, 3},
n2 = {&n3, 2},
n1 = {&n2, 1};
LIST_MAP(&n1, list_print, "%d\n");
}
Re:List Processing in C
by regularfry on Tuesday December 21, 2010 @07:00AM
(#2027556)
There was a spectacular hack involving gcc and dynamic linking which let you do closures in C posted to reddit a few months ago. Naturally I can't find it - anyone save the link?
Sure, C has function pointers. But it doesn't have closures: the things you can do with just a function pointer are fairly limited.
The callback syntax in the post should really be:
...which gets ugly quickly (passing your closure state around as a void*) and doesn't compose well (passing your closure state into your implementations of List_map_, List_fold_, etc.)