lamba in C

Those of you who aren't C programmers can skip this post.

GCC is a great C compiler. It has a ton of nifty little extensions on top of the C language that most people don't know about (or decline to use because they may need to compile their code with another compiler). By combining two of the features, namely nested functions and blocks-within-expressions, I came up with the following nifty macro a few years back. I may have posted to LJ about it then, too. I can't remember. But I've been using it often lately.

#define lambda(r, p, args...) ({static r _f p args _f;})

which lets you define an anonymous function as an expression, much like lambda does in other languages like LISP and Python. Here's a contrived example:

double z;
int flag;
double (*f)(double x);

if (flag) {
f = lambda(double, (double x), {
return x + z;
} else {
f = lambda(double, (double x), {
return x * z;

z = 10;
f(5); // returns 15 if flag is set or 50 if it isn't

While contrived, you could perhaps see how this would be useful if you want to create a function to pass to qsort() but the user could select one of several different sorting criteria. Those with experience in other languages with lambda() probably see why lambda() is so useful, but unfortunately I don't think I can do it justice simply through explanation.

The lambda expression can also be passed as parameter to functions like qsort(), so one doesn't need to bother explicitly creating a function pointer object, either.

The only restriction is that if the containing function returns, the function pointer is bogus.


Leave a Reply