Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created November 10, 2010 16:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmitrySoshnikov/671072 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/671072 to your computer and use it in GitHub Desktop.
// lambda lifting (http://en.wikipedia.org/wiki/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;
}
@monolithed
Copy link

out:

> 5
> Segmentation fault (core dumped)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment