Reputation: 111
And, if it does, how do you use one? (syntax)
Also, why does or why doesn't C support lambda expressions?
Upvotes: 10
Views: 5299
Reputation: 1228
I saw this today: https://github.com/wd5gnr/clambda/blob/master/clambda2.c
See here the code of the link above:
// Example with lambda (needs --std=gnu99)
#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.
Upvotes: 1
Reputation: 52177
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.
Upvotes: 12
Reputation: 882181
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.
Upvotes: 5
Reputation: 370377
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.
Upvotes: 3