Introduction & Syntax
Lambda Expressions · Study material
Lambda expressions in C++ are small anonymous functions you can write right where you need them – as a comparator for std::sort, a predicate for std::count_if, a callback for a button, or a task for a thread. A lambda can capture variables from the surrounding scope, by value or by reference, which makes it far more convenient than a separate function or a hand-written function object. Introduced in C++11 and improved in every standard since (generic lambdas, init captures, constexpr, template lambdas, deducing this), lambdas are now used everywhere in modern C++ and come up in almost every interview. This page explains the syntax, every kind of capture, mutable, generic and template lambdas, std::function, recursion and the common pitfalls with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Lambda syntax and return types
- Capture by value, by reference, default captures, this and *this
- mutable, init captures and move captures
- Generic, template, constexpr and immediately invoked lambdas
- Closure types, function pointers and std::function
- Recursive lambdas and dangling-capture pitfalls
Lambda syntax
The full form is [captures](parameters) specifiers -> return_type { body }. Only the brackets and body are required. The return type is deduced from the return statements, or given with ->. A lambda expression creates an object (a closure) that can be stored in auto, passed to algorithms, or called immediately.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
// [capture](parameters) -> return_type { body }
auto square = [](int x) { return x * x; }; // return type deduced
auto divide = [](int a, int b) -> double { return static_cast<double>(a) / b; };
auto greet = [] { std::cout << "hello "; }; // no parameters: () may be omitted
greet();
std::cout << square(7) << ' ' << divide(7, 2) << ' ';
std::cout << [](int a, int b) { return a + b; }(3, 4) << '\n'; // call immediately
std::vector<int> v{5, -2, 9, -7, 1};
std::sort(v.begin(), v.end(), [](int a, int b) { return std::abs(a) < std::abs(b); }); // inline comparator
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
hello 49 3.5 7 1 -2 5 -7 9
Captures
A lambda can use global and static variables freely, but local variables must be captured:
| Capture | Meaning |
|---|---|
[] | nothing |
[x] | copy of x, taken when the lambda is created |
[&x] | reference to x |
[=] | everything used, by value |
[&] | everything used, by reference |
[=, &x] / [&, x] | default plus exceptions |
[this] / [*this] | the current object by pointer / by copy (C++17) |
[y = expr], [p = std::move(p)] | init capture: a new variable (C++14) |
#include <iostream>
int main() {
int count = 10;
int step = 2;
auto by_value = [count] { return count; }; // copies count NOW
auto by_ref = [&count] { return count; }; // refers to count
auto mixed = [=, &count] { count += step; }; // everything by value except count
auto all_ref = [&] { step *= 10; }; // everything by reference
count = 50;
mixed();
all_ref();
std::cout << by_value() << ' ' << by_ref() << ' ' << count << ' ' << step << '\n';
return 0;
}
10 52 52 20
mutable and init captures
By-value captures are const inside the lambda. mutable allows the lambda to change its own copies – which persist between calls, because they are members of the closure object. Init captures create new variables, and are the way to move objects (like unique_ptr) into a lambda.
#include <iostream>
int main() {
int calls = 0;
// A by-value capture is const inside the lambda; mutable lets the lambda change ITS OWN copy
auto counter = [calls]() mutable { return ++calls; };
std::cout << counter() << counter() << counter() << ' ' << calls << '\n';
auto copy = counter; // the closure object (with its state) is copied
std::cout << copy() << counter() << '\n';
// Init capture (C++14): create a new member variable for the lambda
auto next_id = [id = 1000]() mutable { return id++; };
std::cout << next_id() << ' ' << next_id() << '\n';
return 0;
}
123 0 44 1000 1001
#include <iostream>
#include <memory>
#include <string>
#include <vector>
int main() {
auto data = std::make_unique<std::vector<int>>(std::vector<int>{1, 2, 3});
std::string name = "report";
// Move-only objects can be MOVED into a lambda with an init capture
auto task = [d = std::move(data), title = name + ".csv"] {
int sum = 0;
for (int x : *d) sum += x;
return title + " sum=" + std::to_string(sum);
};
std::cout << task() << ' ' << (data == nullptr) << ' ' << name << '\n';
return 0;
}
report.csv sum=6 1 report
Generic and template lambdas
A parameter declared auto makes the lambda generic: its call operator is a template. C++20 also allows an explicit template parameter list, []<typename T>(…), when you need to name the type.
#include <iostream>
#include <string>
#include <vector>
int main() {
auto twice = [](auto x) { return x + x; }; // C++14 generic lambda
std::cout << twice(21) << ' ' << twice(1.5) << ' ' << twice(std::string("ab")) << '\n';
// C++20 template lambda: name the type to use it inside
auto sum_all = []<typename T>(const std::vector<T>& v) {
T total{};
for (const T& x : v) total += x;
return total;
};
std::cout << sum_all(std::vector<int>{1, 2, 3}) << ' ' << sum_all(std::vector<std::string>{"C", "+", "+"}) << '\n';
// Variadic generic lambda with a fold expression
auto count_args = [](auto... xs) { return sizeof...(xs); };
std::cout << count_args(1, 'a', "x", 2.5) << '\n';
return 0;
}
42 3 abab 6 C++ 4
Capturing this
Inside a member function, [this] captures the object's address, so the lambda sees later changes – and dangles if the object dies first. [*this] (C++17) captures a copy of the whole object. Note that C++20 deprecates the implicit capture of this through [=]; write it explicitly.
#include <functional>
#include <iostream>
#include <string>
#include <vector>
class Button {
std::string label_;
int clicks_ = 0;
public:
explicit Button(std::string l) : label_(std::move(l)) {}
std::function<void()> on_click_ref() { return [this] { ++clicks_; }; } // refers to this object
std::function<std::string()> snapshot() const { return [*this] { return label_ + ":" + std::to_string(clicks_); }; } // C++17: copy of the object
int clicks() const { return clicks_; }
};
int main() {
Button b("Save");
auto click = b.on_click_ref();
auto before = b.snapshot(); // captured a copy with 0 clicks
click(); click(); click();
std::cout << b.clicks() << ' ' << before() << ' ' << b.snapshot()() << '\n';
return 0;
}
3 Save:0 Save:3
Closure types, function pointers and std::function
Every lambda expression has its own unique, unnamed type – use auto or a template to store and pass it. A lambda with no captures converts to an ordinary function pointer. std::function<R(Args...)> can hold any callable with the right signature, which is perfect for callbacks stored in containers, at the cost of type erasure (a possible heap allocation and an indirect call).
#include <functional>
#include <iostream>
#include <map>
#include <string>
int apply(int (*op)(int, int), int a, int b) { return op(a, b); } // C-style callback
int main() {
// A lambda with NO captures converts to a plain function pointer
std::cout << apply([](int a, int b) { return a * b; }, 6, 7) << ' ';
// std::function can store ANY callable with a matching signature, including capturing lambdas
int bonus = 100;
std::map<std::string, std::function<int(int)>> rules{
{"double", [](int x) { return 2 * x; }},
{"bonus", [bonus](int x) { return x + bonus; }},
{"negate", std::negate<int>{}},
};
for (const auto& [name, f] : rules) std::cout << name << '=' << f(21) << ' ';
std::cout << '\n';
// Every lambda has its own unique closure type
auto a = [] { return 1; };
auto b = [] { return 1; };
std::cout << std::is_same_v<decltype(a), decltype(b)> << ' ' << sizeof(a) << ' ' << sizeof([bonus] { return bonus; }) << '\n';
return 0;
}
42 bonus=121 double=42 negate=-21 0 1 4
Recursive lambdas
A lambda cannot simply call itself by name, because its variable is not yet declared inside its own initialiser. C++23 deducing this solves it: the lambda takes this auto self as its first parameter. Older alternatives are std::function or passing the lambda to itself.
#include <functional>
#include <iostream>
int main() {
// C++23 "deducing this": the lambda receives itself as the first parameter
auto fib = [](this auto self, int n) -> long { return n < 2 ? n : self(n - 1) + self(n - 2); };
std::cout << fib(20) << ' ';
// Before C++23: std::function (has overhead) or pass the lambda to itself
std::function<int(int)> fact = [&fact](int n) { return n <= 1 ? 1 : n * fact(n - 1); };
auto gcd = [](auto&& self, int a, int b) -> int { return b == 0 ? a : self(self, b, a % b); };
std::cout << fact(10) << ' ' << gcd(gcd, 84, 36) << '\n';
return 0;
}
6765 3628800 12
Lambdas vs functions vs function objects
| Function | Function object (functor) | Lambda | |
|---|---|---|---|
| Holds state | no (only statics) | yes, as members | yes, via captures |
| Defined where used | no | no | yes |
| Inlined by algorithms | usually not through a pointer | yes | yes |
| Boilerplate | little | a whole class | minimal |
A lambda is really a function object written by the compiler: captures become data members and the body becomes operator() (const unless the lambda is mutable).
Common mistakes
- Dangling reference captures – returning or storing a lambda that captured a local by reference.
- [this] outliving the object – callbacks stored after the object is destroyed.
- Expecting a by-value capture to see later changes – it was copied at creation.
- Modifying a by-value capture without mutable – compile error.
- Overusing [&] and [=] – capture explicitly so the dependencies are visible.
- Using std::function everywhere – prefer auto or templates when you do not need type erasure.
Key points to remember
[captures](params) -> ret { body }; the closure is an object.- By value copies at creation; by reference refers to the original.
- mutable lets a lambda change its own copies; they persist between calls.
- Init captures (
[x = std::move(y)]) create new members and allow moving. - auto parameters make generic lambdas; []<typename T> makes template lambdas.
- Captureless lambdas convert to function pointers; std::function stores any callable.
- Never let a lambda outlive what it captured by reference.
Frequently asked questions
What is a closure in C++?
The object created by evaluating a lambda expression; it contains copies of (or references to) the captured variables.
Are lambdas slower than normal functions?
No – passed directly to templates such as std::sort, they are usually inlined and can be faster than function pointers. Wrapping them in std::function adds a small cost.
Can a lambda capture a global variable?
It does not need to: globals and static variables can be used directly. Only local (automatic) variables are captured.
Where can I learn more?
Read C++ Lambda Expressions and C++ Functions, then practise with the exercises below.