C++ · Module 14 · Lesson 11 min read

Lambda Expressions

Syntax

scss
[captures](parameters) -> return_type { body }

auto add = [](int a, int b) { return a + b; };
add(2, 3);   // 5

The return type is usually deduced. A lambda creates an unnamed function object (a functor).

Captures: using outside variables

CaptureMeaning
[]nothing
[x]copy of x (read-only by default)
[&x]reference to x
[=]copy everything used
[&]reference everything used
[=, &total]copy all, but total by reference
[this] / [*this]access members (pointer / copy of object)
[n = x * 2]init capture: new variable (C++14)
[p = std::move(ptr)]move into the lambda

✅ Prefer explicit captures — [&] and [=] hide what you depend on.

mutable

Copies captured by value are const. mutable lets the lambda modify its own copies:

arduino
auto counter = [n = 0]() mutable { return ++n; };

Generic lambdas (C++14)

[](const auto& a, const auto& b) { return a < b; } — works for any type. C++20 allows template syntax: []<typename T>(T x) {...}.

⚠️ Dangling captures

Capturing a local by reference in a lambda that outlives the function (stored, returned, run on another thread) → undefined behaviour. Capture by value or move.

Immediately invoked lambdas

arduino
const auto config = [&] { /* complex setup */ return result; }();

Initialize a const variable with complex logic.

Where lambdas shine

std::sort comparators, find_if/count_if/remove_if predicates, callbacks, std::thread bodies, std::visit, custom deleters.

Example

C++
#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
#include <vector>

std::function<double(double)> make_discount(double percent) {
    return [percent](double price) { return price * (1 - percent / 100); };   // copy: safe to return
}

int main() {
    auto add = [](int a, int b) { return a + b; };
    std::cout << "add(2, 3) = " << add(2, 3) << '\n';

    std::vector<double> expenses = { 450, 15000, 1200, 300, 800 };
    double limit = 1000;

    int over = static_cast<int>(std::count_if(expenses.begin(), expenses.end(),
                                              [limit](double e) { return e > limit; }));   // capture by value
    std::cout << over << " expenses over " << limit << '\n';

    double total = 0;
    std::for_each(expenses.begin(), expenses.end(), [&total](double e) { total += e; });   // by reference
    std::cout << "total = " << total << '\n';

    std::sort(expenses.begin(), expenses.end(), [](double a, double b) { return a > b; });
    std::cout << "largest first:";
    for (double e : expenses) std::cout << ' ' << e;
    std::cout << '\n';

    auto next_id = [id = 1000]() mutable { return ++id; };   // init capture + mutable state
    std::cout << "ids: " << next_id() << ' ' << next_id() << ' ' << next_id() << '\n';

    auto festival = make_discount(15);
    auto clearance = make_discount(50);
    std::cout << "2000 with 15% off = " << festival(2000) << ", with 50% off = " << clearance(2000) << '\n';

    auto longer = [](const auto& a, const auto& b) { return a.size() < b.size(); };   // generic lambda
    std::vector<std::string> words = { "save", "budget", "a", "expense" };
    std::cout << "longest word: " << *std::max_element(words.begin(), words.end(), longer) << '\n';

    const std::string level = [&] {                          // immediately invoked lambda
        if (total > 15000) return "high";
        if (total > 5000) return "medium";
        return "low";
    }();
    std::cout << "spending level: " << level << '\n';
    return 0;
}

/* Output:
add(2, 3) = 5
2 expenses over 1000
total = 17750
largest first: 15000 1200 800 450 300
ids: 1001 1002 1003
2000 with 15% off = 1700, with 50% off = 1000
longest word: expense
spending level: high
*/