Last active
March 17, 2016 10:29
-
-
Save mikaelj/48d3d9157005eb3f0171 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Anonymous functions using GCC statement expressions. (from http://stackoverflow.com/questions/10405436/anonymous-functions-using-gcc-statement-expressions) | |
* | |
* They capture variables, too! | |
* | |
* Output: | |
Timer at 0x7fffffffde70 | |
Callback w/ cookie 0x7fffffffde70, truth 42. | |
*/ | |
#include <stdio.h> | |
#define lambda(return_type, function_body) \ | |
({ \ | |
return_type __fn__ function_body \ | |
__fn__; \ | |
}) | |
typedef void (*callback_t)(void *); | |
typedef struct { | |
void *data; | |
int started; | |
callback_t callback; | |
} timer_t; | |
void start(timer_t *t, void *data, callback_t callback) | |
{ | |
t->data = data; | |
t->callback = callback; | |
} | |
void run(timer_t *t) | |
{ | |
t->callback(t->data); | |
} | |
void second(timer_t *t) | |
{ | |
run(t); | |
} | |
int main(int argc, char **argv) | |
{ | |
int truth = 42; | |
timer_t timer; | |
printf("Timer at %p\n", &timer); | |
start(&timer, &timer, lambda ( | |
void, (void *cookie) { | |
printf("Callback w/ cookie %p, truth %d.\n", cookie, truth); | |
})); | |
second(&timer); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment