Lambda expression in C++

Previous: C++

Lambda expressions, also known as lambdas or closures, were added in C++11 and refined further in later versions. They allow you to define an unnamed function object which can be nested inside of other functions.

Although lambdas behave a lot like functions, they are not functions themselves. The type of a lambda expression is a unique, unnamed, non-union class type generated by the compiler. Specifically, they define an overloaded function call operator (operator()), which makes them functors (also called function objects).

They are especially useful for short, one-off function objects, such as those passed to standard algorithms.

Some of the primary benefits of lambda expressions are:

General Syntax:

[ captureClause ] ( parameters ) -> returnType { statements; }

Example: A lambda to square a number

#include <iostream>

int main()
{
    auto square = [](int x) -> int { return x * x; };
    std::cout << square(5) << std::endl; // Output: 25 return 0; }
}