#include #include // are there closures in C? typedef int (*intfun)(int); // defines intfun to represent type int->int intfun makeacc(int x) // make an instance of an accumulator { int y; // Making this static won't solve problem. y = x; // neither will changing it to a pointer to heap memory int g(int z) { y = y+z; return y; } return &g; } int main() { int (*h)(int); h = (int (*)(int))makeacc(1); printf("h %d \n",h(4)); printf("h %d \n",h(2)); printf("h %d \n",h(2)); int (*h2)(int); h2 = (int (*)(int))makeacc(1); printf("h2 %d \n",h2(3)); printf("h2 %d \n",h2(3)); printf("h %d \n",h(3)); exit(0); }//main /* Problem: C runtime does not implement closures. A variable is only local or global. There are no arbitrary levels of scope. y is only allocated on the stack, and is quickly rewritten by other function calls. Using a static variable does not really change this - because static really makes it global. You cannot have two different INSTANCES of the accumulator function. Even using heap allocation manually won't help: int *y = (int*)malloc(sizeof(int)); still won't solve the problem because the pointer itself is still on the stack (or shared if static). We can only emulate closures at a much lower level in C: For example, let g take an additional parameter representing a user-defined data structure that represents the closure. We would also need routines to access/modify this data structure. */