How to implement a Lamda macro in C?

2024-09-07

As as coder, I think giving a right name to a variable is annoying. In many program language we can use Lamda function to avoid it. However, The C language don't provide this grammar feature for us. I spend few minutes writting a macro to implementing this featrue. Here is the example, It can be compiled in gcc, but no in g++.

#include <stdio.h>

#define LAMDBA(return_type, args_type, block)                                  \
    ({                                                                         \
        return_type _ args_type block;                                         \
        _;                                                                     \
    })

int main(int argc, char *argv[]) {
    int b = LAMDBA(int, (int a, int b), {
        int c = a * a;
        int d = b * 2;
        return c + d;
    })(12, 13);

    printf(""%d\n"", b);

    return 0;
}