Skip to content

Instantly share code, notes, and snippets.

@gdetor
Created February 7, 2023 00:32
Show Gist options
  • Save gdetor/c038f0fc7604feda11c5c54294bd6d99 to your computer and use it in GitHub Desktop.
Save gdetor/c038f0fc7604feda11c5c54294bd6d99 to your computer and use it in GitHub Desktop.
Closure in C
#include <stdio.h>
typedef struct TClosure {
int (*code)(struct TClosure *env, int);
int state;
} Closure;
int call(Closure *c, int x) {
return c->code(c, x);
}
int adder_code(Closure *env, int x) {
return env->state + x;
}
int multiplier_code(Closure *env, int x) {
return env->state * x;
}
Closure make_closure(int op, int k) {
Closure c;
c.state = k;
c.code = (op == '+' ? adder_code : multiplier_code);
return c;
}
int main(int argc, const char *argv[]) {
Closure c1 = make_closure('+', 10);
Closure c2 = make_closure('*', 3);
printf("c1(3) = %i, c2(3) = %i\n",
call(&c1, 3), call(&c2, 3));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment