The anonymous function can be implemented in the C language by means of a macro definition, as follows:
| 123456 |
#define lambda(return_type, function_body) \({ \ return_type $thisfunction_body \ $this; \})#define $ lambda |
The definition takes advantage of GCC's expansion of the C language (a block of code wrapped up in braces can return a value), a macro definition that returns $this (function pointers), and if we need a function that returns two integers, we can also encapsulate the macro again as follows:
| 1 |
#define add2int(function_body) $(int, (int _a, int _b){function_body}) |
Then we can use the macro as follows (for all elements of an integer array):
| 123456789101112131415161718 |
int sum(int *arr, int length, int (*add)(int, int));int main(int argc, char **argv){ int arr[] = { [0 ... 9] = 1, [10 ... 89] = 2, [90 ... 99] = 3 }; int ret = sum(arr, sizeof(arr)/sizeof(int), add2int(int c = _a + _b; return c;)); //add2int返回一个求两个整数和的函数 printf("sum of arr is %d\n", ret);}int sum(int *arr, int length, int (*add)(int, int)){ int sum = 0; for (int i=0; i < length; i++) { sum = add(sum, arr[i]); } return sum;} |
Of course, you can also use the Lambda macro directly, note that Function_body needs to include the return type of the function and the argument list, replacing the 6th line of code with:
| 1234 |
int ret = SUM (arr, sizeof (arr)/ sizeof ( int Code class= "CPP Color1 bold" >int int Code class= "CPP Plain" >_a, int _b) { Code class= "CPP Spaces" >&NBSP;&NBSP;&NBSP;&NBSP; int c = _a + _b; &NBSP;&NBSP;&NBSP;&NBSP; return C; |
Of course such code is certainly inefficient, and superfluous, here is just a simple example
From for notes (Wiz)
C language Implements anonymous functions