开发者

Does C use lambda expressions?

开发者_JS百科And, if it does, how do you use one? (syntax)

Also, why does or why doesn't C support lambda expressions?


No, C has no support for lambda expressions.

If you're willing to use C++, Boost has a library that emulates lambdas. Also, C++0x will have built-in support for lambda expressions.

There wasn't a huge demand for lambda expression support in C at the time, so the language didn't support it.


C does not support lambda expressions, nor any other ways (within the language's standard) to dynamically create functions -- all functions, per the standard, are created at compile time. I guess the reason is to keep the language small, simple, lean, and very fast, with hardly any "runtime library" support necessary -- crucial for a language that's so widely used in programming operating systems, device drivers, embedded applications, and so forth.


No, C doesn't have lambda expressions (or any other way to create closures).

This is likely so because C is a low-level language that avoids features that might have bad performance and/or make the language or run-time system more complex.


I saw this today: https://github.com/wd5gnr/clambda/blob/master/clambda2.c

See here the code of the link above:

#include <stdio.h>


float thelist[]={ 3.141, 6.02, 42.0, 0.7 };

#define lambda(lambda$_ret, lambda$_args, lambda$_body)\
  ({\
    lambda$_ret lambda$__anon$ lambda$_args\
      lambda$_body\
    &lambda$__anon$;\
  })


float average_apply(float (*fn)(float inp))
{
    int i,n=sizeof(thelist)/sizeof(thelist[0]);
    float avg=0.0;
    for (i=0;i<n;i++)
    {
        avg+=fn(thelist[i]);
        printf("Running sum=%f\n", avg);
    }

    return avg/n;
}

int main(int argc, char *argv[])
{
    printf("%f\n",average_apply(lambda(float,(float x),{ return 2*x; })));
    printf("%f\n",average_apply(lambda(float,(float x),{ return x/3.0; })));

    return 0;
}

And works fine in gcc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜