In STL Algorithms and Iterators we kept writing tiny functions directly inside a function call, like [](int x) { return x * 2; }. These are lambda expressions, added in C++11 and improved in almost every standard since.
Before lambdas, giving std::sort a custom comparison meant writing a separate named function or a whole functor class (a class with operator(), from Operator Overloading) somewhere far away from where it was used. Lambdas let you write that logic right where you need it, and, more importantly, let it use local variables of the surrounding function. In this chapter we learn the full syntax, how captures really work, what the compiler generates, and the traps that cause dangling references.
What Is a Lambda?
A lambda expression creates an unnamed function object, called a closure, that can be called like a function and can capture variables from the scope where it is written.
The general form is:
[ captures ] ( parameters ) specifiers -> return_type { body }
│ │ │ │
│ │ │ └─ optional; usually deduced
│ │ └─ optional: mutable, constexpr, static (C++23), noexcept
│ └─ like a normal parameter list; can be omitted if empty
└─ which outside variables the body may use, and how (copy or reference)The smallest lambda is []{}: no captures, no parameters, does nothing.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
// 1. A lambda stored in a variable and called like a function
auto square = [](int x) { return x * x; };
std::cout << "square(7) = " << square(7) << '\n';
// 2. A lambda passed directly to an algorithm
std::vector<int> v = {4, 9, 1, 7};
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); // descending
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
// 3. A lambda with no parameters, called immediately with ()
[] { std::cout << "Hello from a lambda\n"; }();
// 4. An explicit return type with ->
auto divide = [](int a, int b) -> double { return static_cast<double>(a) / b; };
std::cout << "7 / 2 = " << divide(7, 2) << '\n';
}Output:
square(7) = 49
9 7 4 1
Hello from a lambda
7 / 2 = 3.5Some points worth noticing:
Each lambda has a unique, unnamed type that only the compiler knows, so we store it with
auto.The return type is deduced from the
returnstatements, just like anautofunction. If there are severalreturns, they must all deduce the same type. Use-> typewhen you want to force a type, as individe.Writing
()right after the lambda calls it immediately. This is called an immediately invoked lambda; we will see a practical use later.
Captures: Using Outside Variables
A lambda body cannot use local variables of the enclosing function unless it captures them. (Global variables, static locals and constants usable at compile time can be used without capture.) The capture list says which variables and how:
| Capture | Meaning |
|---|---|
[] | Capture nothing |
[x] | Copy x into the lambda when the lambda is created |
[&x] | Refer to the original x |
[=] | Copy every local variable that the body uses |
[&] | Refer to every local variable that the body uses |
[=, &x] | Copy everything used, except x by reference |
[&, x] | Reference everything used, except x by copy |
[this] | Capture the this pointer (members are accessed through it) |
[*this] (C++17) | Copy the whole current object into the lambda |
[y = expr] (C++14) | Init capture: create a new member y initialized from expr |
[&y = x] (C++14) | Init capture by reference: y is another name for x |
#include <iostream>
int main() {
int bonus = 10;
auto byValue = [bonus](int marks) { return marks + bonus; }; // copies bonus NOW
auto byRef = [&bonus](int marks) { return marks + bonus; }; // refers to bonus
bonus = 50; // change the original after creating the lambdas
std::cout << "byValue(60) = " << byValue(60) << '\n'; // still uses 10
std::cout << "byRef(60) = " << byRef(60) << '\n'; // sees 50
int count = 0;
auto increment = [&count] { ++count; }; // modify an outside variable
increment();
increment();
std::cout << "count = " << count << '\n';
int a = 1, b = 2;
auto f = [=] { return a + b; }; // capture everything used, by value
auto g = [&] { a *= 10; b *= 10; }; // capture everything used, by reference
auto h = [=, &b] { b = a + 100; }; // a by value, b by reference
g();
h();
std::cout << "f() = " << f() << ", a = " << a << ", b = " << b << '\n';
}Output:
byValue(60) = 70
byRef(60) = 110
count = 2
f() = 3, a = 10, b = 101Let us trace the last line carefully, because it is a typical exam trick:
fis created whena = 1, b = 2, and copies both. Whatever happens later,f()returns 1 + 2 = 3.his also created before anything changes, so its copy ofais 1. It holdsbby reference.g()runs: the realabecomes 10 andbbecomes 20.h()runs: it sets the realbto its own copy ofa(1) + 100 = 101.
The key rule: a by-value capture takes a snapshot at the moment the lambda is created, not when it is called.
Which Should You Prefer?
Prefer listing captures explicitly ([limit], [&total]) rather than [=] or [&]. The reader then sees exactly what the lambda depends on. Capture by reference when the lambda must modify the outside variable or the object is expensive to copy, and the lambda will not outlive that variable. Capture by value when the lambda may be stored or returned.
mutable Lambdas and Init Captures
By default, variables captured by value are read-only inside the body. The reason is that the generated operator() is a const member function (we will see this in the next section). Adding the mutable specifier removes that const, so the lambda can change its own copies. The original variables are never affected.
#include <iostream>
int main() {
int start = 100;
// auto bad = [start] { return ++start; }; // error: start is read-only inside
auto ticket = [start]() mutable { return ++start; }; // modifies its OWN copy
std::cout << ticket() << ' ' << ticket() << ' ' << ticket() << '\n';
std::cout << "start is still " << start << '\n';
auto copy = ticket; // copying a lambda copies its captured state
std::cout << "ticket: " << ticket() << ", copy: " << copy() << '\n';
// Init capture (C++14): create a new member variable inside the lambda
auto counter = [n = 0]() mutable { return ++n; };
counter();
counter();
std::cout << "counter called " << counter() << " times\n";
}Output:
101 102 103
start is still 100
ticket: 104, copy: 104
counter called 3 timesA mutable lambda remembers its state between calls: the first three calls returned 101, 102, 103. Copying a lambda copies that state too, which is why ticket and copy each returned 104 independently. This matters when you pass a stateful lambda by value to an algorithm: the algorithm works on a copy, and your original does not see the changes.
The counter example uses an init capture (C++14). n is not a variable from outside; it is a brand-new member of the closure, initialized to 0. Init captures can also move an object into a lambda instead of copying it, which is the only way to capture move-only types; we return to that in Move Semantics & Rvalue References.
What the Compiler Generates
A lambda is not a new kind of function. It is syntactic sugar for a class. For each lambda expression the compiler writes a unique class (the closure type) with:
one data member for each variable captured by value (by-reference captures are usually stored as references or pointers);
a constructor that initializes those members from the captured variables;
an
operator()containing your body, markedconstunless you wrotemutable.
Then the lambda expression itself becomes "create one object of that class". Here is a hand-written class that behaves like a lambda:
#include <iostream>
// Roughly what the compiler generates for: [limit](int x) { return x > limit; }
class GreaterThan {
int limit; // one member per captured variable
public:
explicit GreaterThan(int l) : limit(l) {}
bool operator()(int x) const { return x > limit; } // const unless the lambda is mutable
};
int main() {
int limit = 40;
auto lambda = [limit](int x) { return x > limit; };
GreaterThan functor(limit);
std::cout << std::boolalpha;
std::cout << lambda(50) << ' ' << functor(50) << '\n';
std::cout << lambda(30) << ' ' << functor(30) << '\n';
std::cout << "sizeof(lambda) = " << sizeof(lambda) << '\n';
std::cout << "sizeof(functor) = " << sizeof(functor) << '\n';
auto empty = [] { return 1; };
std::cout << "sizeof(captureless lambda) = " << sizeof(empty) << '\n';
}Output (GCC 15 on x86-64):
true true
false false
sizeof(lambda) = 4
sizeof(functor) = 4
sizeof(captureless lambda) = 1The lambda and the hand-written functor behave identically and even have the same size: one int. A lambda with no captures has no data, but every C++ object needs a size of at least 1 byte. This is why lambdas are zero-overhead: calling one is a normal member function call that the compiler can easily inline, which often makes std::sort with a lambda faster than C's qsort with a function pointer.
Source: int limit = 40;
auto lambda = [limit](int x) { return x > limit; };
Compiler: class __lambda_1 { // unique, unnamed type
int limit; // captured copy
public:
__lambda_1(int l) : limit(l) {}
bool operator()(int x) const { return x > limit; }
};
auto lambda = __lambda_1{limit}; // object created HERE (snapshot)Every lambda expression gets its own type, even if two lambdas are written with identical text. That is why you cannot assign one lambda to another variable declared with a different lambda's type, and why we need std::function when we want to store "any callable with this signature".
Generic Lambdas (C++14) and Template Lambdas (C++20)
If a parameter is declared auto, the closure's operator() becomes a function template (see Templates). The same lambda then works for many types. C++20 adds an explicit template parameter list []<typename T>(...), useful when you need the type's name, for example to declare a local variable of that type or to accept only a vector<T>.
#include <iostream>
#include <string>
#include <vector>
int main() {
using namespace std::string_literals;
// Generic lambda (C++14): auto parameters make operator() a template
auto add = [](auto a, auto b) { return a + b; };
std::cout << add(2, 3) << '\n';
std::cout << add(1.5, 2.25) << '\n';
std::cout << add("Hello, "s, "World"s) << '\n';
// Template lambda (C++20): name the type to express constraints
auto sumAll = []<typename T>(const std::vector<T>& v) {
T total{};
for (const T& x : v) total += x;
return total;
};
std::cout << sumAll(std::vector<int>{1, 2, 3, 4}) << '\n';
std::cout << sumAll(std::vector<double>{0.5, 0.25}) << '\n';
// Generic lambda that prints any container
auto print = [](const auto& container) {
for (const auto& x : container) std::cout << x << ' ';
std::cout << '\n';
};
print(std::vector<char>{'a', 'b', 'c'});
print(std::vector<std::string>{"GATE", "2027"});
}Output:
5
3.75
Hello, World
10
0.75
a b c
GATE 2027 add worked for int, double and std::string (the s suffix makes a std::string literal, from Strings), because the compiler instantiated a separate operator() for each combination of argument types.
Lambdas with STL Algorithms
This is where you will use lambdas most often: as comparators and predicates.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Student {
std::string name;
int marks;
};
int main() {
std::vector<Student> cls = {
{"Asha", 78}, {"Ravi", 91}, {"Meena", 65}, {"John", 91}, {"Farah", 42}
};
// Sort by marks (high to low); ties broken by name
std::sort(cls.begin(), cls.end(), [](const Student& a, const Student& b) {
if (a.marks != b.marks) return a.marks > b.marks;
return a.name < b.name;
});
for (const auto& s : cls) std::cout << s.name << ' ' << s.marks << '\n';
// The pass mark comes from a variable, so we capture it
int passMark = 50;
auto passed = std::count_if(cls.begin(), cls.end(),
[passMark](const Student& s) { return s.marks >= passMark; });
std::cout << "Passed: " << passed << '\n';
// First student whose name starts with 'M'
auto it = std::find_if(cls.begin(), cls.end(),
[](const Student& s) { return s.name.front() == 'M'; });
if (it != cls.end()) std::cout << "Found: " << it->name << '\n';
// Add grace marks to everyone, then remove those still failing (C++20 erase_if)
int grace = 5;
std::for_each(cls.begin(), cls.end(), [grace](Student& s) { s.marks += grace; });
std::erase_if(cls, [passMark](const Student& s) { return s.marks < passMark; });
std::cout << "After grace: " << cls.size() << " students, lowest = "
<< cls.back().name << ' ' << cls.back().marks << '\n';
}Output:
John 91
Ravi 91
Asha 78
Meena 65
Farah 42
Passed: 4
Found: Meena
After grace: 4 students, lowest = Meena 70The comparator for std::sort must define a strict weak ordering: it must return false for equal elements. Writing a.marks >= b.marks instead of > breaks this rule and is undefined behaviour; with many equal elements it can even make std::sort read out of bounds. Notice also that for_each took its parameter as Student& so that it could modify the elements.
Storing Lambdas: auto, Templates and std::function
There are three ways to keep or pass a lambda:
| Way | Example | Pros | Cons |
|---|---|---|---|
auto variable | auto f = [](int x){...}; | Zero overhead | Only inside one scope; each lambda has its own type |
| Template parameter | template<typename F> void run(F f) | Zero overhead, can inline | Code must be in a header; a new instantiation per lambda type |
std::function<R(Args...)> | std::function<int(int)> f = ...; | One type for any callable with that signature; can be stored in containers and members | Type erasure costs an indirect call and possibly a heap allocation for large captures |
#include <functional>
#include <iostream>
#include <map>
#include <string>
// Accepts any callable with the signature int(int, int)
int apply(const std::function<int(int, int)>& op, int a, int b) {
return op(a, b);
}
// Template version: no std::function overhead, the call can be inlined
template <typename F>
int applyFast(F op, int a, int b) {
return op(a, b);
}
int main() {
// Different lambdas have different types, but std::function can hold any of them
std::map<std::string, std::function<int(int, int)>> ops;
ops["add"] = [](int a, int b) { return a + b; };
ops["sub"] = [](int a, int b) { return a - b; };
int factor = 3;
ops["scaledMul"] = [factor](int a, int b) { return a * b * factor; };
for (const auto& [name, op] : ops)
std::cout << name << "(6, 2) = " << op(6, 2) << '\n';
std::cout << apply(ops["add"], 10, 5) << ' '
<< applyFast([](int a, int b) { return a % b; }, 10, 4) << '\n';
// A captureless lambda converts to an ordinary function pointer
int (*fp)(int, int) = [](int a, int b) { return a > b ? a : b; };
std::cout << "max via function pointer: " << fp(8, 13) << '\n';
std::function<int(int, int)> empty;
std::cout << std::boolalpha << "empty is callable? " << static_cast<bool>(empty) << '\n';
try {
empty(1, 2);
} catch (const std::bad_function_call& e) {
std::cout << "caught std::bad_function_call\n";
}
}Output:
add(6, 2) = 8
scaledMul(6, 2) = 36
sub(6, 2) = 4
15 2
max via function pointer: 13
empty is callable? false
caught std::bad_function_callNotice two extra facts in this program:
A lambda with no captures can be converted to an ordinary function pointer. That lets you pass it to C APIs such as
qsort. A capturing lambda cannot, because a plain function pointer has nowhere to keep the captured data.Calling an empty
std::functionthrowsstd::bad_function_call(see Exception Handling).
C++23 also added std::move_only_function, a cheaper variant of std::function that can hold move-only callables, and C++26 adds std::function_ref for non-owning callbacks. For everyday code, auto and templates come first and std::function when you truly need a single storable type.
Capturing this Inside Member Functions
Inside a member function, a lambda that uses data members must capture this. [this] captures only the pointer, so the lambda sees the current values of members, and it dangles if the object dies first. [*this] (C++17) copies the entire object into the closure, which is safe to keep after the object is gone.
#include <algorithm>
#include <iostream>
#include <vector>
class Classroom {
std::vector<int> marks{35, 72, 48, 90, 55};
int passMark = 50;
public:
int countPassed() const {
// [this] lets the lambda use members (passMark) through the this pointer
return static_cast<int>(std::count_if(marks.begin(), marks.end(),
[this](int m) { return m >= passMark; }));
}
auto makeReporter() const {
// [*this] (C++17) stores a COPY of the whole object inside the lambda
return [*this] { std::cout << "Snapshot pass mark: " << passMark << '\n'; };
}
void setPassMark(int p) { passMark = p; }
};
int main() {
Classroom c;
std::cout << "Passed: " << c.countPassed() << '\n';
auto report = c.makeReporter();
c.setPassMark(40);
std::cout << "Passed now: " << c.countPassed() << '\n';
report(); // still prints 50: it has its own copy
}Output:
Passed: 3
Passed now: 4
Snapshot pass mark: 50Before C++20, [=] inside a member function silently captured this (the pointer, not a copy of the object), which surprised many programmers who believed everything was copied. C++20 deprecated this implicit capture; write [=, this] (allowed only since C++20) or [*this] to say what you mean.
Recursive Lambdas
A lambda cannot refer to its own variable name inside its body, because the variable's type is not known until the lambda expression is complete. There are two solutions:
#include <functional>
#include <iostream>
int main() {
// auto fact = [](int n) { return n <= 1 ? 1 : n * fact(n - 1); };
// error: 'fact' is used before its type is known
// Before C++23: go through std::function (has some runtime overhead)
std::function<long long(int)> fact = [&fact](int n) -> long long {
return n <= 1 ? 1 : n * fact(n - 1);
};
std::cout << "10! = " << fact(10) << '\n';
// C++23 "deducing this": the lambda receives itself as the first parameter
auto fib = [](this auto self, int n) -> long long {
return n < 2 ? n : self(n - 1) + self(n - 2);
};
std::cout << "fib(30) = " << fib(30) << '\n';
}Output:
10! = 3628800
fib(30) = 832040The C++23 feature is called deducing this (explicit object parameter). The first parameter, marked with this, receives the closure object itself, so the lambda can call self(...). It needs -std=c++23 (GCC 14+, Clang 18+, MSVC 17.2+). It is faster than the std::function approach and has no risk of dangling. For a captureless lambda, taking self by value is cheap; for a lambda with large captures, write this const auto& self.
Immediately Invoked, constexpr and static Lambdas
#include <iostream>
#include <string>
int main() {
int score = 83;
// Immediately invoked lambda: lets a const variable get a value from complex logic
const std::string grade = [score] {
if (score >= 90) return "A";
if (score >= 75) return "B";
if (score >= 60) return "C";
return "F";
}();
std::cout << "Grade: " << grade << '\n';
// Lambdas are implicitly constexpr when possible (C++17)
constexpr auto cube = [](int x) { return x * x * x; };
static_assert(cube(3) == 27); // evaluated at compile time
int table[cube(2)] = {}; // array size 8, known at compile time
std::cout << "table has " << sizeof(table) / sizeof(table[0]) << " elements\n";
// C++23 static lambda: no captures allowed, operator() has no hidden object
auto twice = [](int x) static { return 2 * x; };
std::cout << "twice(21) = " << twice(21) << '\n';
}Output:
Grade: B
table has 8 elements
twice(21) = 42Immediately invoked lambda: a neat way to initialize a
constvariable that needs if/else logic or a loop, instead of declaring it non-const and assigning it later.constexpr lambdas (C++17): a lambda's
operator()is automaticallyconstexprwhen its body allows it, so it can be evaluated at compile time, here to check astatic_assertand to size an array.static lambdas (C++23): a captureless lambda can be marked
static, which makesoperator()a static member function with no hidden object parameter. This is a small optimization; capturing anything in a static lambda is a compile error.
The Dangling Reference Trap
Capturing by reference stores a reference, and C++ does not extend the life of the referenced variable. If the lambda outlives the variable, calling it is undefined behaviour:
#include <functional>
#include <iostream>
std::function<int()> makeCounter() {
int count = 0; // local variable, destroyed when we return
return [&count] { return ++count; }; // BUG: captures a reference to it
}
int main() {
auto next = makeCounter();
std::cout << next() << '\n'; // undefined behavior: count no longer exists
}Compiled with -fsanitize=address (output trimmed; addresses vary):
=================================================================
==2668==ERROR: AddressSanitizer: stack-use-after-return on address 0x6e9f4a9f00b0 ...
READ of size 4 at 0x6e9f4a9f00b0 thread T0
#0 ... in operator() dangling_asan.cpp:6Without the sanitizer anything can happen. On our test machine (g++ 15) the plain -O0 build crashed with a segmentation fault, while the -O2 build quietly printed a garbage number. With another compiler or flag it might even print the "expected" 1, which makes the bug even more dangerous because it can pass testing. The fix is to give the lambda its own state: return [count = 0]() mutable { return ++count; };. The same danger applies to [this] when the lambda is stored somewhere (for example in a callback list or a thread) that lives longer than the object. Rule of thumb: if a lambda escapes the current scope, capture by value.
Lambda Features by Standard
| Standard | Feature |
|---|---|
| C++11 | Lambdas, captures by value/reference, mutable, trailing return type |
| C++14 | Generic lambdas (auto parameters), init captures [x = expr], return type deduction for any body |
| C++17 | constexpr lambdas (implicit when possible), [*this] |
| C++20 | Template parameter lists []<typename T>, lambdas in unevaluated contexts, default-constructible captureless lambdas, implicit this capture via [=] deprecated, pack expansion in init captures |
| C++23 | Deducing this (recursive lambdas), static lambdas, attributes on lambdas, () may be omitted even when specifiers like mutable are present |
Common Mistakes
1. Expecting a by-value capture to see later changes
[x] copies x when the lambda is created. If you need the latest value at call time, capture by reference (and make sure the variable outlives the lambda).
2. Returning or storing a lambda that captures locals by reference
As shown above, this leads to dangling references. Watch out especially for [&] in lambdas passed to threads or saved in containers.
3. Trying to modify a by-value capture without mutable
[n] { ++n; } does not compile, because operator() is const. Add mutable, and remember it changes only the lambda's copy.
4. Inconsistent return types
[](bool b) { if (b) return 1; return 2.5; } fails because the returns deduce int and double. Add -> double.
5. Using <= or >= in a sort comparator
Comparators must return false for equal elements (strict weak ordering). Use < or >.
6. Using std::function where auto is enough
std::function<int(int)> f = [](int x){ return x + 1; }; works, but adds type-erasure overhead for no benefit. Use auto unless you need to store different callables in the same variable or container.
Interview / GATE-Style Questions
Q1. What is the output? int x = 5; auto f = [x] { return x * 2; }; x = 20; std::cout << f();
10. The by-value capture copied x (5) when f was created. Changing x later does not affect the lambda's copy.
Q2. What is a closure? How is it related to a lambda expression?
A lambda expression is the source code. Evaluating it creates a closure: an object of a unique, compiler-generated class (the closure type) that holds the captured variables as data members and has an operator() containing the lambda body.
Q3. Why are by-value captures read-only by default, and how do you change that?
The generated operator() is a const member function, so it cannot modify data members (the captured copies). Writing mutable after the parameter list makes operator() non-const. The changes affect only the closure's own copies, which persist across calls of that closure object.
Q4. Can a lambda be converted to a function pointer?
Only if it captures nothing. A captureless lambda has an implicit conversion to a pointer to a function with the same signature. A capturing lambda needs storage for its captures, which a plain function pointer cannot provide; use std::function or a template parameter instead.
Q5. What is the output? int c = 0; auto f = [c]() mutable { return ++c; }; auto g = f; f(); f(); std::cout << g() << ' ' << c;
1 0. g is a copy of f made when its internal c was 0, so its own first call returns 1. Calls to f changed only f's copy. The outer c was never modified.
Q6. How can you write a recursive lambda in C++23 without std::function?
Use an explicit object parameter (deducing this): auto f = [](this auto self, int n) -> int { return n <= 1 ? 1 : n * self(n - 1); };. The closure receives itself as self and can call it.
Summary
A lambda
[captures](params) -> ret { body }creates a closure: an object of a unique compiler-generated class with anoperator().By-value captures are snapshots taken at creation; by-reference captures refer to the original and can dangle if the lambda outlives it.
Captured copies are read-only unless the lambda is
mutable; init captures[n = 0](C++14) create new members.Generic lambdas (
autoparameters, C++14) and template lambdas (C++20) work for many types.Store lambdas with
autoor pass them as template parameters for zero overhead; usestd::functionwhen you need one type for many callables.Inside classes,
[this]captures the pointer and[*this](C++17) copies the object.C++23 adds deducing
thisfor recursive lambdas andstaticlambdas.
Lambdas made it easy to pass behaviour around. Next we tackle safe ownership of memory: in Smart Pointers, objects clean up after themselves so that the leaks and dangling pointers from Dynamic Memory Allocation disappear.