Lambda expressions in C

C does not have built-in support for lambda expressions, but if you are using gcc or clang, it is actually quite easy to implement them using a simple macro.

This trick relies on two C extensions: nested functions and statement expressions. Both are available in gcc and clang.

Here is a small program that could benefit from lambda expressions, written in conventional C:

// A function taking a function pointer as argument.
// Call the function `f` `nb` times.
void func(int nb, void (*f)(int)) {
    int i;
    for (i = 0; i < nb; i++) f(i);
}

void callback(int v) {
    printf("%d\n", v);
}

int main()
{
    func(4, callback);
}

The first change we can do is use nested functions to put the callback definition inside the main function:

int main()
{
    void callback(int v) { printf("%d\n", v); }
    func(4, callback);
}

The second change comes from using a statement expression to create the callback function directly in the argument list:

int main()
{
    func(4, ({
        void callback(int v) { printf("%d\n", v); }
        callback;
    });
}

Now we are almost there. Since the statement expression scope does not leak to the rest of the function, we can use any name for the callback, so we are going to use _. We can also put the code into a macro so that we do not have to repeat the name of the callback (as required by the statement expression). And the final result is:

#define LAMBDA(c_) ({ c_ _;})

int main()
{
    func(4, LAMBDA(void _(int v) {
        printf("%d\n", v);
    }));
}

There is one limitation to this: the lambda is only valid during the scope of the calling function, so we have to be careful not to use it for asynchronous callbacks.

The remaining question is: should we use such a trick in production code?


If you liked this, you can follow me on twitter: @guillaumecherea