C++ - Lambda Expressions in C++

Lambda expressions are a feature introduced in C++11 that allow programmers to write anonymous functions directly inside the code. An anonymous function is a function that does not have a name. Lambda expressions are mainly used when a small function is required for a short period of time, especially when working with algorithms such as sorting, searching, or iterating through containers.

Instead of defining a separate function elsewhere in the program, a lambda expression lets you write the function at the exact place where it is needed. This helps make the code shorter and easier to understand.

Basic Syntax

The general syntax of a lambda expression is:

[capture](parameters) {
    // function body
};

Capture
The capture clause specifies which variables from the surrounding scope can be used inside the lambda function. Variables can be captured by value or by reference.

Parameters
These are similar to parameters of a normal function.

Function Body
This contains the code that will be executed when the lambda function is called.

Example

#include <iostream>
using namespace std;

int main() {
    auto add = [](int a, int b) {
        return a + b;
    };

    cout << add(5, 3);
    return 0;
}

Explanation:

  • [] indicates the capture list.

  • (int a, int b) are the parameters.

  • The lambda function returns the sum of the two numbers.

  • The result of add(5,3) is printed.

Example with Capture

#include <iostream>
using namespace std;

int main() {
    int x = 10;

    auto show = [x]() {
        cout << x;
    };

    show();
    return 0;
}

In this example, the variable x is captured by value inside the lambda expression, allowing it to be used within the function.

Advantages of Lambda Expressions

  1. They reduce the need to write separate small functions.

  2. They make the code more compact and readable.

  3. They are very useful when working with Standard Template Library (STL) algorithms.

  4. They allow functions to be defined exactly where they are needed.

Conclusion

Lambda expressions provide a convenient way to create short, temporary functions in C++. They improve code readability and are widely used in modern C++ programming, especially with STL algorithms and functional-style programming.