C language Implements anonymous functions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.