--- title: "Lambda expressions in C++" description: "C++ lambda expressions explained: syntax, capture lists, capturing by value, mutable lambdas, and using lambdas with standard algorithms." date: 2023-04-06 last_modified_at: 2026-10-02 keywords: [C++, lambda expressions, C++11, closures, capture list] --- # Lambda Expressions in C++ Lambda expressions were introduced in C++11 and provide a concise way to create anonymous function objects. ## Basic Syntax The basic syntax of a lambda expression is: ```cpp [capture-list](parameter-list) -> return-type { function-body } ``` Where: - `capture-list`: Specifies which variables from the surrounding scope are accessible - `parameter-list`: Similar to function parameters - `return-type`: Optional, compiler can often deduce it - `function-body`: The code to execute ## Examples ### Simple Lambda ```cpp auto add = [](int a, int b) { return a + b; }; std::cout << add(5, 3); // Outputs: 8 ``` ### Capturing Variables ```cpp int multiplier = 5; auto multiply = [multiplier](int x) { return x * multiplier; }; std::cout << multiply(3); // Outputs: 15 ``` ### Mutable Lambda By default, variables captured by value cannot be modified. Use the `mutable` keyword to allow modification: ```cpp int counter = 0; auto increment = [counter]() mutable { return ++counter; }; std::cout << increment(); // Outputs: 1 std::cout << counter; // Outputs: 0 (original not modified) ``` Lambda expressions are commonly used with algorithms from the standard library, such as `std::sort`, `std::for_each`, and `std::transform`.