tags:

views:

182

answers:

3

And, if it does, how do you use one? (syntax)

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

+2  A: 

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.

In silico
... love you. And now I love Stack Overflow, because that was quick!
shosh
+1  A: 

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.

sepp2k
+2  A: 

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.

Alex Martelli
Lambda expression does not require dynamically creating a function. It's just creating an object that refers to a (possibly nameless) function that's already compiled.
Mike Dunlavey
@Mike, in C you can refer to existing functions via a pointer (indeed, a _mention_ of the function's name "decays" to a pointer to it, so that's quite elegant and doable).
Alex Martelli
@Alex: I think Mike has a point. You could in theory have in C a lambda-style syntax with no closures, to define within an expression a function like `x => x*x` and evaluate to a pointer to that function, all without breaking the constraint you mention. It's only when you want your lambda to access its surrounding scope that it becomes impossible with a typical C function pointer consisting just of the address of the code. Whether such context-free functions should rightly be called "lambdas" or not, I don't know.
Steve Jessop
And now I'm wondering what (if anything) could be done in a C implementation where function pointers are bigger than object pointers, so that they can contain a code address as normal but also a context pointer (which would be null for named C functions, and point to a chunk of stack for anonymous functions defined using some extension syntax). Obviously that's way more hassle than the C standard wants to inflict on implementers. But possibly less hassle than C++ pointers-to-members-of-virtual-base-classes.
Steve Jessop
@Steve, Clang has "lambda" support in C using *blocks*. See the spec at http://clang.llvm.org/docs/BlockLanguageSpec.txt and http://stackoverflow.com/questions/2395040/how-do-clang-blocks-work
Johannes Schaub - litb