Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
// lambda lifting (
// in GNU C; use inner functions which are not closures
// of course, but have access to free variables
// by Dmitry A. Soshnikov
#include <stdio.h>
// a pointer to a function type
typedef int (*funcPtr)(int);
int foo(int x)
int firstInner(int y)
return x + y;
return firstInner(3);
funcPtr bar(int x)
int secondInner(int y)
return x + y;
// return the function
return secondInner;
int main()
printf("%d\n", foo(2)); // OK, 5
// returned function
funcPtr f1 = bar(3);
printf("%d\n", f1(2)); // also OK, 5
// however, it's not a closure of course
// but just lambda lifting;
// an attemt to call it again with
// different arg will cause that the
// first one will return a new result also
funcPtr f2 = bar(5);
printf("%d\n", f2(2)); // OK, 7
// see that we have the same function
printf("first: %p, second: %p\n", f1, f2);
// call the fist one again
printf("%d\n", f1(2)); // segmentation fault
return 0;

This comment has been minimized.

Copy link

@monolithed monolithed commented Apr 12, 2012


> 5
> Segmentation fault (core dumped)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment