Topic 87 of 91 11. Additional C++ Topics Added Interactive Tutorial

Lambda Expressions in C++: Writing Inline Anonymous Functions

7 mins read Last updated: 26 Sep 2026 19,919 views

Direct Answer & Core Concept

Lambda expressions are inline anonymous function objects (closures) defined using the syntax [captures](parameters) -> return_type { body }. The capture clause determines how variables from the enclosing scope are accessed: by value ([=]), by reference ([&]), explicitly ([x, &y]), or by moving ([p = std::move(ptr)]).

Detailed Explanation & Mechanics

1. Lambda Anatomy:

Architecture Diagram
┌── Capture Clause (Context access)
  │     ┌── Parameter List
  │     │       ┌── Trailing Return Type (Optional)
  │     │       │        ┌── Function Body
┌─┴─┐ ┌─┴──┐ ┌──┴──┐ ┌───┴────────────────┐
[ x ] (int y) -> int { return x + y; }

2. Capture Modes:

  • []: Captures nothing.
  • [=]: Captures all used outer variables by value (read-only copy).
  • [&]: Captures all used outer variables by reference (can mutate original).
  • [this]: Captures the current class object pointer.
  • [val = 10]: Generalized lambda capture (C++14).

Runnable Code Example: Lambda Expressions in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {12, 45, 68, 23, 89, 90, 34};
    int threshold = 50;
    int matchCount = 0;

    // Lambda capturing 'threshold' by value and 'matchCount' by reference
    auto countHigh = [&matchCount, threshold](int n) {
        if (n > threshold) {
            ++matchCount;
            return true;
        }
        return false;
    };

    std::cout << "Numbers above " << threshold << ":\n";
    for (int num : numbers) {
        if (countHigh(num)) {
            std::cout << "  - " << num << "\n";
        }
    }
    std::cout << "Total matches: " << matchCount << "\n";

    // Generic Lambda (C++14 auto parameter)
    auto printTwice = [](auto item) {
        std::cout << item << " | " << item << "\n";
    };
    printTwice("OperateTools");
    printTwice(42);
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What is the type of a lambda expression in C++?

A: Each lambda expression generates a unique, anonymous closure class type created by the compiler. You can store lambdas using `auto`, function templates, or `std::function`.
Q

Q: What does the `mutable` specifier on a lambda do?

A: By default, variables captured by value are `const` inside the lambda body. Adding `mutable` (`[x]() mutable { ++x; }`) allows modifying the local copy of the captured variable.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

• Prefer explicit captures ([x, &y]) over default captures ([=], [&]) to avoid accidental lifetime dangling bugs.
• Use generic lambdas ([](auto val)) for concise polymorphic callables.
• Prefer lambdas over std::bind in modern C++ for better compiler optimization and readability.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.