What a lambda function is
A lambda function is a small, unnamed function that you write inline, usually at the place where you need it. The C++ standard calls it a lambda expression. Lambdas were added in C++11, so your compiler needs to be set to C++11 or a later standard.
Here is a lambda that doubles a number:
#include <iostream>
int main() {
auto twice = [](int x) { return x * 2; };
std::cout << twice(5) << "\n"; // 10
}
What’s the point of lambda functions? They let you write a short piece of behavior where it is used, without declaring a separate named function. That matters most when you pass behavior to other code, which is covered below.
Syntax
A lambda has up to four parts:
[capture list] (parameters) -> return type { body }
- The capture list
[ ]names the variables from the surrounding code that the lambda may use, and whether each one is copied or referred to. - The parameters
( )work like a normal function’s. They can be empty. - The return type
-> typeis optional. You can leave it out in most code. - The body
{ }holds the code that runs when the lambda is called.
A lambda that uses nothing from outside starts with an empty []:
#include <iostream>
int main() {
auto greet = []() { std::cout << "Hello from a lambda\n"; };
greet(); // prints: Hello from a lambda
}
You can also call a lambda right where you write it, by adding () after the closing brace:
#include <iostream>
int main() {
[]() { std::cout << "Runs once, right away\n"; }();
}
C# writes its lambdas with an arrow instead, as in x => x * 2. What is the use of => in C#? It is the lambda arrow, and it shows up in other places in C# too. C++ does not use => at all.
Capturing variables from the surrounding code
A lambda can use an outside variable only if that variable appears in the capture list. There are two ways to capture one:
- By value
[x]: the lambda gets its own copy ofx, made when the lambda is created. - By reference
[&x]: the lambda uses the samex, so it sees later changes to it.
#include <iostream>
int main() {
int factor = 3;
auto by_value = [factor](int x) { return x * factor; };
auto by_ref = [&factor](int x) { return x * factor; };
factor = 10;
std::cout << by_value(2) << "\n"; // 6, the copy still holds 3
std::cout << by_ref(2) << "\n"; // 20, reads the current factor
}
You can also use default capture modes:
[=]copies every outside variable that the body uses.[&]refers to every outside variable that the body uses.- You can mix them, as in
[=, &total], which copies most variables but refers tototal.
Default modes are convenient, but they hide what a lambda depends on. In longer code, naming each variable is easier to follow.
Changing a copy with mutable
A variable captured by value is read-only inside the lambda, unless you add mutable after the parameter list. Changes then apply to the lambda’s own copy, not to the variable outside:
#include <iostream>
int main() {
int n = 0;
auto next = [n]() mutable { return ++n; };
std::cout << next() << "\n"; // 1
std::cout << next() << "\n"; // 2
std::cout << n << "\n"; // 0, the outside n did not change
}
Initializing a capture
Since C++14, a capture can create a new name with a value of your choice:
#include <iostream>
int main() {
auto add_ten = [offset = 10](int x) { return x + offset; };
std::cout << add_ten(5) << "\n"; // 15
}
Using lambdas with standard algorithms
Lambdas are most often passed to functions from the standard library, such as std::sort and std::count_if. Each of these takes a lambda that decides what to do with the elements.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {4, 1, 7, 3};
// Sort from largest to smallest
std::sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; });
// Count the values above a limit
int limit = 3;
auto big = std::count_if(nums.begin(), nums.end(),
[limit](int x) { return x > limit; });
std::cout << big << "\n"; // 2, the values 7 and 4
}
std::count_if returns a signed difference type rather than int, so auto is a safe choice for the variable.
Passing lambdas to functions
Can you put a function as a parameter? Yes. A function template can take a lambda as its argument and call it like any other function:
#include <iostream>
template <typename Func>
void run_twice(Func f) {
f();
f();
}
int main() {
run_twice([]() { std::cout << "hi\n"; }); // prints hi twice
}
If the parameter should have one fixed type for every lambda, use std::function instead of a template. The section on storing lambdas below shows how.
Generic lambdas and return types
Since C++14, a lambda can take auto parameters, which makes it work with more than one type:
#include <iostream>
int main() {
auto add = [](auto a, auto b) { return a + b; };
std::cout << add(2, 3) << "\n"; // 5
std::cout << add(1.5, 2.0) << "\n"; // 3.5
}
In C++11, a lambda whose body had more than one statement needed an explicit return type, written with ->. C++14 and later can work out the return type from the return statements. Writing the return type yourself is still useful when you want a specific type:
auto half = [](double x) -> double { return x / 2; };
C++20 also lets you name a template parameter for a lambda:
auto twice_all = []<typename T>(T value) { return value * 2; };
Storing lambdas
What is the type of a lambda? Each lambda expression gets its own unnamed class type, so you cannot write its name in your code. Because of that, you usually store a lambda in one of two ways:
auto, for a local variable. The variable takes the lambda’s own type.std::function, when you need one declared type that can hold any lambda or function with a matching signature. This suits a member variable or astd::vectorof callbacks.
#include <functional>
#include <iostream>
int main() {
std::function<int(int, int)> op = [](int a, int b) { return a * b; };
std::cout << op(3, 4) << "\n"; // 12
}
Common mistakes
Returning a lambda that refers to a local variable
A lambda that captures a local variable by reference keeps a reference to it. When the function returns, that variable no longer exists, and calling the lambda later has undefined behavior:
auto make_getter() {
int x = 5;
return [&x]() { return x; }; // Wrong: x is gone after the return
}
Capturing by value gives the lambda its own copy, which lives as long as the lambda does:
auto make_getter() {
int x = 5;
return [x]() { return x; }; // Fine: the lambda owns a copy
}
Forgetting mutable
If a lambda changes a variable it captured by value, the compiler reports an error until you add mutable after the parameter list. If you want the outside variable to change, capture it by reference instead.
Capturing this
Inside a class, a lambda that uses a member needs this in its capture list, as in [this]. The object must still exist when the lambda is called. Default captures such as [=] and [&] can capture this without you noticing, so name it yourself when it matters.
Using a lambda for long or repeated logic
A lambda is best for short logic used in one place. If the logic is long, or used in several places, a named function is easier to read and test. A lambda also cannot easily refer to itself by the name it is stored under, so recursive logic usually fits a named function better.
Are lambdas faster?
A lambda is not automatically faster or slower than a normal function. When the compiler can see the lambda’s code, it can often inline it, so the cost is usually small. If speed matters for your program, measure it.
Quick reference
| Capture | Meaning |
|---|---|
[] |
Uses nothing from the surrounding code |
[x] |
Copies x when the lambda is created |
[&x] |
Refers to x |
[=] |
Copies every outside variable the body uses |
[&] |
Refers to every outside variable the body uses |
[this] |
Lets the body use the members of the current object |
Add mutable after the parameter list to change the copies made by value. Store a lambda with auto in a local variable, or with std::function when you need one declared type.