This behavior seems to be specfic to newer versions of Clang, and is a language extension called "blocks".

The Wikipedia article on C "blocks" also provides information which supports this claim:

Blocks are a non-standard extension added by Apple Inc. to Clang's implementations of the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages. Blocks are supported for programs developed for Mac OS X 10.6+ and iOS 4.0+, although third-party runtimes allow use on Mac OS X 10.5 and iOS 2.2+ and non-Apple systems.

Emphasis above is mine. On Clang's language extension page, under the "Block type" section, it gives a brief overview of what the Block type is:

Like function types, the Block type is a pair consisting of a result value type and a list of parameter types very similar to a function type. Blocks are intended to be used much like functions with the key distinction being that in addition to executable code they also contain various variable bindings to automatic (stack) or managed (heap) memory.

GCC also has something similar to blocks called lexically scoped nested functions. However, there are some key differences also note in the Wikipedia articles on C blocks:

Blocks bear a superficial resemblance to GCC's extension of C to support lexically scoped nested functions. However, GCC's nested functions, unlike blocks, must not be called after the containing scope has exited, as that would result in undefined behavior.

GCC-style nested functions also require dynamic creation of executable thunks when taking the address of the nested function. [...].

Emphasis above is mine.

Answer from Chris on Stack Overflow
🌐
Hackaday
hackaday.com › 2019 › 09 › 11 › lambdas-for-c-sort-of
Lambdas For C — Sort Of | Hackaday
November 2, 2023 - Modern C++ has lambda expressions. However, in C you have to define a function by name and pass a pointer — not a huge problem, but it can get messy if you have a lot of callback functions that you use only one time. It’s just hard to think up that many disposable function names. However, if you use gcc, there are ...
Top answer
1 of 2
10

This behavior seems to be specfic to newer versions of Clang, and is a language extension called "blocks".

The Wikipedia article on C "blocks" also provides information which supports this claim:

Blocks are a non-standard extension added by Apple Inc. to Clang's implementations of the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages. Blocks are supported for programs developed for Mac OS X 10.6+ and iOS 4.0+, although third-party runtimes allow use on Mac OS X 10.5 and iOS 2.2+ and non-Apple systems.

Emphasis above is mine. On Clang's language extension page, under the "Block type" section, it gives a brief overview of what the Block type is:

Like function types, the Block type is a pair consisting of a result value type and a list of parameter types very similar to a function type. Blocks are intended to be used much like functions with the key distinction being that in addition to executable code they also contain various variable bindings to automatic (stack) or managed (heap) memory.

GCC also has something similar to blocks called lexically scoped nested functions. However, there are some key differences also note in the Wikipedia articles on C blocks:

Blocks bear a superficial resemblance to GCC's extension of C to support lexically scoped nested functions. However, GCC's nested functions, unlike blocks, must not be called after the containing scope has exited, as that would result in undefined behavior.

GCC-style nested functions also require dynamic creation of executable thunks when taking the address of the nested function. [...].

Emphasis above is mine.

2 of 2
7

the C standard does not define lambdas at all but the implementations can add extensions.

Gcc also added an extension in order for the programming languages that support lambdas with static scope to be able to convert them easily toward C and compile closures directly.

Here is an example of extension of gcc that implements closures.

#include <stdio.h>

int(*mk_counter(int x))(void)
{
    int inside(void) {
        return ++x;
    }
    return inside;
}

int
main() {
    int (*counter)(void)=mk_counter(1);
    int x;
    x=counter();
    x=counter();
    x=counter();
    printf("%d\n", x);
    return 0;
}
Discussions

c++ - What is a lambda, and why would it be useful? - Software Engineering Stack Exchange
The lambda calculus in its most basic form has two operations: Abstraction (creating an (anonymous) function) and application (apply a function). Abstraction is performed using the λ operator, giving the lambda calculus its name. ... Anonymous functions are often called "lambdas", "lambda ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
December 10, 2010
simple lambda like functions in C
These nested functions aren’t standard C and they won’t work on Clang or MSVC. More on reddit.com
🌐 r/C_Programming
26
11
March 12, 2024
c++ - What is a lambda expression, and when should I use one? - Stack Overflow
The algorithm was much more speedy when using a lambda than a proper function! The compiler is Visual C++ 2013. ... Here is another really good reference which explains very well what are lambda expressions in C++: Microsoft.com: Lambda expressions in C++. I especially like how well it explains ... More on stackoverflow.com
🌐 stackoverflow.com
Why does C not have lambdas/anonymous function expressions?
There are two basic ways to implement closures: A custom calling convention: Callers are aware they're calling a closure and so pass the closure context to the callee, perhaps as a hidden argument. Closures are nearly always implemented this way, including in C++. For C, as a lingua franca platforms would need to define this calling convention / ABI so that different implementers could all each others closures just as they can call each others functions. Since this doesn't exist, closures in language implementations using this approach are incompatible with C interop (ex. can't turn a C++ closure into a function pointer). Build a trampoline by allocating a little bit of executable memory, essentially like using a small JIT compiler. Callers do not need to be aware they're calling a closure, and a plain C calling convention is sufficient. GNU C closures are implemented this way, as are CPython's ctypes callbacks. However, frequently allocating executable memory requires significant trade-offs in performance or security. It may not even be possible on some platforms. This is also an implicit allocation — which is not in the spirit of C — and someone has to manage its lifetime. (GNU C manages it by using an automatic allocation.) Unless you're willing to make the trade-offs in the second approach — which is available to you if you use GCC — neither fits C well. More on reddit.com
🌐 r/C_Programming
35
6
August 7, 2022
🌐
Reddit
reddit.com › r/c_programming › why does c not have lambdas/anonymous function expressions?
r/C_Programming on Reddit: Why does C not have lambdas/anonymous function expressions?
August 7, 2022 -

It would not seem to hard to implement to allow a programmer to use a construct similar to:

int (*add)(int, int) = (int(int x, int y)){return x+y;};

This would simplify code that requires callback functions such as qsort or bsearch or various UI libraries that use callbacks to define, for example, a buttons behavior when pressed. Is there any specific reason they elected not to support this, and require us to define named static functions instead?

Top answer
1 of 7
8
There are two basic ways to implement closures: A custom calling convention: Callers are aware they're calling a closure and so pass the closure context to the callee, perhaps as a hidden argument. Closures are nearly always implemented this way, including in C++. For C, as a lingua franca platforms would need to define this calling convention / ABI so that different implementers could all each others closures just as they can call each others functions. Since this doesn't exist, closures in language implementations using this approach are incompatible with C interop (ex. can't turn a C++ closure into a function pointer). Build a trampoline by allocating a little bit of executable memory, essentially like using a small JIT compiler. Callers do not need to be aware they're calling a closure, and a plain C calling convention is sufficient. GNU C closures are implemented this way, as are CPython's ctypes callbacks. However, frequently allocating executable memory requires significant trade-offs in performance or security. It may not even be possible on some platforms. This is also an implicit allocation — which is not in the spirit of C — and someone has to manage its lifetime. (GNU C manages it by using an automatic allocation.) Unless you're willing to make the trade-offs in the second approach — which is available to you if you use GCC — neither fits C well.
2 of 7
6
Why are people obsessed with making C like python or whatever language they learned first? It's like asking why my bicycle only has two wheels, when your red wagon has four.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › lambda-expression-in-c
Lambda Expression in C++ - GeeksforGeeks
Lambda expressions in C++ are anonymous, inline functions introduced in C++11 that allow writing small pieces of logic directly at the place of use.
Published   February 28, 2026
🌐
Medium
madhawapolkotuwa.medium.com › mastering-lambda-functions-in-c-a-complete-guide-with-practical-examples-e2cc3f10dfce
Mastering Lambda Functions in C++: A Complete Guide with Practical Examples | by Madhawa Polkotuwa | Medium
November 1, 2024 - Introduction: Lambda functions in C++ provide a concise and flexible way to create inline, anonymous functions. Introduced in C++11, and enhanced in later versions, Lambdas are useful in situations where you need short snippets of code without ...
🌐
Cprogramming.com
cprogramming.com › c++11 › c++11-lambda-closures.html
C++11 - Lambda Closures, the Definitive Guide - Cprogramming.com
How to begin Get the book · C tutorial C++ tutorial Game programming Graphics programming Algorithms More tutorials
Find elsewhere
🌐
Built In
builtin.com › software-engineering-perspectives › c-plus-plus-lambda
C++ Lambda Expressions Explained | Built In
A lambda in C++ is an expression used to simplify code when defining anonymous function objects (functors). Lambdas allow for functors to be defined directly where they are invoked or be passed as function arguments.
🌐
Wikipedia
en.wikipedia.org › wiki › Anonymous_function
Anonymous function - Wikipedia
February 18, 2026 - In computer programming, an anonymous function (function literal, lambda function, or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function ...
🌐
TutorialsPoint
tutorialspoint.com › significance-of-lambda-function-in-c-cplusplus
Significance of Lambda Function in C/C++
February 5, 2021 - Lambda Function − Lambda functions are anonymous inline functions that don't require any implementation outside the scope where they are defined. They provide a concise way to write small functions directly at the point of use.
🌐
Quora
cstdspace.quora.com › How-do-we-write-and-use-lambda-functions-in-pure-C-indirectly-instead-of-C
How do we write and use lambda functions in pure C indirectly instead of C++? - C Programmers - Quora
Answer (1 of 3): There aren’t any lambdas in C, so you can’t. You can create a context structure, populate it, and give it as an argument to a callback function, but the syntax is grotty and it is not nicely handled for things that take callbacks don’t have a void* argument for that context.
🌐
Quora
quora.com › How-do-we-write-and-use-lambda-functions-in-pure-C-indirectly-instead-of-C
How do we write and use lambda functions in pure C indirectly instead of C++? - Quora
Answer (1 of 5): https://en.wikipedia.org/wiki/Anonymous_function#C_(non-standard_extension) > C (non-standard extension)[edit] The anonymous function is not supported by standard C programming language, but supported by some C dialects, such as GCC[52] and Clang. GCC[edit] GNU Compiler Colle...
Top answer
1 of 3
43
  • Lambda calculus

The lambda calculus is a computation model invented by Alonzo Church in the 30s. The syntax and semantics of most functional programming languages are directly or indirectly inspired by the lambda calculus.

The lambda calculus in its most basic form has two operations: Abstraction (creating an (anonymous) function) and application (apply a function). Abstraction is performed using the λ operator, giving the lambda calculus its name.

  • Lambda expressions
  • Lambda functions

Anonymous functions are often called "lambdas", "lambda functions" or "lambda expressions" because, as I said above, λ was the symbol to create anonymous functions in the lambda calculus (and the word lambda is used to create anonymous functions in many lisp-based languages for the same reason).

  • Lambda programming

This is not a commonly used term, but I assume it means programming using anonymous functions or programming using higher-order functions.


A bit more information about lambdas in C++0x, their motivation and how they relate to function pointers (a lot of this is probably a repeat of what you already know, but I hope it helps explain the motivation of lambdas and how they differ from function pointers):

Function pointers, which already existed in C, are quite useful to e.g. pass a comparison function to a sorting function. However there are limits to their usefulness:

For example if you want to sort a vector of vectors by the ith element of each vector (where i is a run-time parameter), you can't solve this with a function pointer. A function that compares two vectors by their ith element, would need to take three arguments (i and the two vectors), but the sorting function would need a function taking two arguments. What we'd need is a way to somehow supply the argument i to the function before passing it to the sorting function, but we can't do this with plain C functions.

To solve this, C++ introduced the concept of "function objects" or "functors". A functor is basically an object which has an operator() method. Now we can define a class CompareByIthElement, which takes the argument i as a constructor argument and then takes the two vectors to be compared as arguments to the operator() method. To sort a vector of vectors by the ith element we can now create a CompareByIthElement object with i as an argument and then pass that object to the sorting function.

Since function objects are just objects and not technically functions (even though they are meant to behave like them), you can't make a function pointer point to a function object (you can of course have a pointer to a function object, but it would have a type like CompareByIthElement* and thus not be a function pointer).

Most functions in the C++ standard library which take functions as arguments are defined using templates so that they work with function pointers as well as function objects.

Now to lambdas:

Defining a whole class to compare by the ith element is a bit verbose if you're only ever going to use it once to sort a vector. Even in the case where you only need a function pointer, defining a named function is sub-optimal if it's only used once because a) it pollutes the namespace and b) the function is usually going to be very small and there isn't really a good reason to abstract the logic into its own function (other than that you can't have function pointers without defining a function).

So to fix this lambdas were introduced. Lambdas are function objects, not function pointers. If you use a lambda literal like x1, x2{bla} code is generated which basically does the following:

  1. Define a class which has two member variables (x1 and x2) and an operator() with the arguments (y1 and y2) and the body bla.
  2. Create an instance of the class, setting the member variables x1 and x2 to the values of the variables x1 and x2 currently in scope.

So lambdas behave like function objects, except that you can't access the class that's generated to implement a lambda in any way other than using the lambda. Consequently any function that accepts functors as arguments (basically meaning any non-C function in the standard library), will accept lambdas, but any function only accepting function pointers will not.

2 of 3
18

Basically, lambda functions are functions you create "on the fly". In C++1x they could be used to improve on its support for functional programming:

std::for_each( begin, end, [](int i){std::cout << i << '\n';} );

This will roughly result in code similar to this one:

struct some_functor {
  void operator()(int i) {std::cout << i << '\n';}
};

std::for_each( begin, end, some_functor() );

If you need some_functor just for this one call to std::for_each(), then that lambda function has several advantages over it:

  • what's done in the loop is specified right where the looping function is called
  • it relieves you from writing some of the boiler-plate code
  • there's no functor lying around at some namespace scope that makes everyone looking at the code wondering what it is needed for
🌐
LinkedIn
linkedin.com › pulse › lamda-unction-c-amit-nadiger
Lamda function in C++
June 18, 2023 - Lambda functions or lambda expressions are a feature that was introduced in C++11. It is a concise way to define small and anonymous functions that can be used anywhere in the program.
🌐
Reddit
reddit.com › r/c_programming › simple lambda like functions in c
r/C_Programming on Reddit: simple lambda like functions in C
March 12, 2024 -

I was diving in reddit and I found the following post

I thought: maybe it is possible to do something similar in C with macros or something along those lines.

After some research, I found the following topic on GCC manual:
Statements and Declarations in Expressions

Well, with this construction, it's possible to instruct the compiler to define a function and call it in place, like we can do with lambdas. Look the example bellow:

#include <stdio.h>
int call_callback(void (*callback)()){
    callback();
}

void foo() {
    printf("foo\n");
}

int main(void) {
    call_callback(foo);
    call_callback(({
        void _() {
            printf("this is a lambda?\n");
        }
        (void (*)())_;
    }));
}

For me, it's very interesting. We encounter many situations and libraries that deal with callback functions, and personally, I often find myself declaring simple functions that are only called once. I believe that in these cases, this construct would work very well.

However, debugging it might be challenging.

Top answer
1 of 11
1808

The problem

C++ includes useful generic functions like std::for_each and std::transform, which can be very handy. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function.

#include <algorithm>
#include <vector>

namespace {
  struct f {
    void operator()(int) {
      // do something
    }
  };
}

void func(std::vector<int>& v) {
  f f;
  std::for_each(v.begin(), v.end(), f);
}

If you only use f once and in that specific place it seems overkill to be writing a whole class just to do something trivial and one off.

In C++03 you might be tempted to write something like the following, to keep the functor local:

void func2(std::vector<int>& v) {
  struct {
    void operator()(int) {
       // do something
    }
  } f;
  std::for_each(v.begin(), v.end(), f);
}

however this is not allowed, f cannot be passed to a template function in C++03.

The new solution

C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the struct f. For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form:

void func3(std::vector<int>& v) {
  std::for_each(v.begin(), v.end(), [](int) { /* do something here*/ });
}

Lambda functions are just syntactic sugar for anonymous functors.

Return types

In simple cases the return type of the lambda is deduced for you, e.g.:

void func4(std::vector<double>& v) {
  std::transform(v.begin(), v.end(), v.begin(),
                 [](double d) { return d < 0.00001 ? 0 : d; }
                 );
}

however when you start to write more complex lambdas you will quickly encounter cases where the return type cannot be deduced by the compiler, e.g.:

void func4(std::vector<double>& v) {
    std::transform(v.begin(), v.end(), v.begin(),
        [](double d) {
            if (d < 0.0001) {
                return 0;
            } else {
                return d;
            }
        });
}

To resolve this you are allowed to explicitly specify a return type for a lambda function, using -> T:

void func4(std::vector<double>& v) {
    std::transform(v.begin(), v.end(), v.begin(),
        [](double d) -> double {
            if (d < 0.0001) {
                return 0;
            } else {
                return d;
            }
        });
}

"Capturing" variables

So far we've not used anything other than what was passed to the lambda within it, but we can also use other variables, within the lambda. If you want to access other variables you can use the capture clause (the [] of the expression), which has so far been unused in these examples, e.g.:

void func5(std::vector<double>& v, const double& epsilon) {
    std::transform(v.begin(), v.end(), v.begin(),
        epsilon -> double {
            if (d < epsilon) {
                return 0;
            } else {
                return d;
            }
        });
}

You can capture by both reference and value, which you can specify using & and = respectively:

  • [&epsilon, zeta] captures epsilon by reference and zeta by value
  • [&] captures all variables used in the lambda by reference
  • [=] captures all variables used in the lambda by value
  • [&, epsilon] captures all variables used in the lambda by reference but captures epsilon by value
  • [=, &epsilon] captures all variables used in the lambda by value but captures epsilon by reference

The generated operator() is const by default, with the implication that captures will be const when you access them by default. This has the effect that each call with the same input would produce the same result, however you can mark the lambda as mutable to request that the operator() that is produced is not const.

2 of 11
955

What is a lambda expression?

The C++ concept of a lambda expression originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming.

In C++, the minimal lambda expression looks like:

[]{} // lambda with no parameters that does nothing 

[] is the capture list and {} the function body.

The full syntax for a lambda-expression, including attributes, noexcept/throw-specifications, requires-clauses, etc. is more complex.

The capture list

The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either:

  1. a value: [x]
  2. a reference [&x]
  3. any variable currently in scope by reference [&]
  4. same as 3, but by value [=]
  5. capturing this and making member functions callable within the lambda [this]

You can mix any of the above in a comma separated list [x, &y].

Init-captures (C++14)

An element of the capture list can now be initialized with =, which is called init-capture. This allows renaming of variables and to capture by moving. An example taken from the standard:

int x = 4;
auto y = [&r = x, x = x+1]()->int {
            r += 2;
            return x+2;
         }();  // Updates ::x to 6, and initializes y to 7.

and one taken from Wikipedia showing how to capture with std::move:

auto ptr = std::make_unique<int>(10); // See below for std::make_unique
auto lambda = [ptr = std::move(ptr)] {return *ptr;};

The template parameters (C++20)

Since C++20, lambda expressions can have a template-parameter-list:

[]<int N>() {};

Such a generic lambda is like a non-template struct with a call operator template:

struct __lambda {
    template <int N> void operator()() const {}
};

The parameter list

The parameter-declaration-clause is the same as in any other C++ function. It can be omitted completely when there are no parameters, meaning that [](){} is equivalent to []{}.

Generic Lambdas (C++14)

Lambdas with an auto parameter are generic lambdas. auto would be equivalent to T here if T were a type template argument somewhere in the surrounding scope):

[](auto x, auto y) { return x + y; }

This works just like a C++20 abbreviated function template:

struct __lambda {
    // C++20 equivalent
    void operator()(auto x, auto y) const { return x + y; }
    // pre-C++20 equivalent
    template <typename T, typename U>
    void operator()(T x, U y) const { return x + y; }
};

Return type (possibly deduced)

If a lambda has only one return statement, the return type can be omitted and has the implicit type of decltype(return_statement).

The return type can also be provided explicitly using trailing return type syntax:

[](int x) -> int { return x; }

Improved Return Type Deduction (C++14)

C++14 allows deduced return types for every function and does not restrict it to functions of the form return expression;. This is also extended to lambdas. By default, the return type of a lambda is deduced as if its return type was declared auto.

Mutable lambda (C++14)

If a lambda is marked mutable (e.g. []() mutable { }) it is allowed to mutate the values that have been captured by value.

mutable means that the call operator of the lambda's type does not have a const qualifier.

The function body

A block-statement will be executed when the lambda is actually called. This becomes the body of the call operator.

Use cases

The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope.

🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › cpp › lambda-expressions-in-cpp
Lambda expressions in C++ | Microsoft Learn
In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.
🌐
FasterCapital
fastercapital.com › content › Functional-Programming-with-C---Lambdas--A-Practical-Guide.html
Functional Programming with C: Lambdas: A Practical Guide - FasterCapital
Lambda expressions in C++ are anonymous functions that can be treated as objects. They are used to define functions on-the-fly, without the need for a separate declaration. As such, they are often used to define small, single-use functions that ...
🌐
Cppreference
en.cppreference.com › w › cpp › language › lambda.html
Lambda expressions (since C++11) - cppreference.com
Constructs a closure (an unnamed function object capable of capturing variables in scope). ... A variable __func__ is implicitly defined at the beginning of body, with semantics as described here. The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class ...