C++ Lambda Expressions

Lambda expressions in C++ provide a concise way to define anonymous functions directly within your code. They are useful for short-term, inline operations such as callbacks, sorting, and filtering. Lambda expressions were introduced in C++11.

Syntax

[capture_list](parameters) -> return_type {
    // Function body
}

Explanation of Components

  • Lambda expressions are anonymous functions that can be defined inline.
  • Variables can be captured by value (=) or by reference (&) to use them inside the lambda.
  • Useful in algorithms, event handlers, and functional-style programming.

Next Topic

This concludes the C++ Advanced Topics section. Next, you can explore the C++ Standard Template Library (STL).

  • capture_list: Captures variables from the surrounding scope (e.g., [&x, y]).
  • parameters: List of parameters like a normal function (can be empty).
  • return_type: Optional, specifies the return type. Can be omitted if compiler can deduce it.
  • Function body contains the code to execute.

Example: Basic Lambda Expression

#include <iostream>
using namespace std;

int main() {
    // Lambda to add two numbers
    auto add = [](int a, int b) {
        return a + b;
    };

    int result = add(5, 3);
    cout << "Sum: " << result << endl;

    return 0;
}

Output

Sum: 8

Example: Lambda Capturing Variables

#include <iostream>
using namespace std;

int main() {
    int x = 10;
    int y = 20;

    // Capture x by reference and y by value
    auto multiply = [&x, y]() {
        return x * y;
    };

    cout << "Result: " << multiply() << endl;

    x = 15; // Modify x to see effect
    cout << "Result after changing x: " << multiply() << endl;

    return 0;
}

Output

Result: 200
Result after changing x: 300

Important Notes

  • Lambda expressions are anonymous functions that can be defined inline.
  • Variables can be captured by value (=) or by reference (&) to use them inside the lambda.
  • Useful in algorithms, event handlers, and functional-style programming.

Next Topic

This concludes the C++ Advanced Topics section. Next, you can explore the C++ Standard Template Library (STL).