What tools are there for functional programming in C?

Adam Rosenfield picture Adam Rosenfield · Oct 19, 2008 · Viewed 49.9k times · Source

I've been thinking a lot lately about how to go about doing functional programming in C (not C++). Obviously, C is a procedural language and doesn't really support functional programming natively.

Are there any compiler/language extensions that add some functional programming constructs to the language? GCC provides nested functions as a language extension; nested functions can access variables from the parent stack frame, but this is still a long way away from mature closures.

For example, one thing that I think could be really useful in C is that anywhere where a function pointer is expected, you could be able to pass a lambda expression, creating a closure which decays into a function pointer. C++0x is going to include lambda expressions (which I think is awesome); however, I'm looking for tools applicable to straight C.

[Edit] To clarify, I'm not trying to solve a particular problem in C that would be more suited to functional programming; I'm merely curious about what tools are out there if I wanted to do so.

Answer

Joe D picture Joe D · Jul 31, 2010

You can use GCC's nested functions to simulate lambda expressions, in fact, I have a macro to do it for me:

#define lambda(return_type, function_body) \
  ({ \
    return_type anon_func_name_ function_body \
    anon_func_name_; \
  })

Use like this:

int (*max)(int, int) = lambda (int, (int x, int y) { return x > y ? x : y; });