Table of Contents
A lambda function is an unnamed function that can be defined directly at the location where it is needed. Lambda expressions provide a concise way to create callable objects without declaring a separate named function.
A lambda expression can capture variables from its surrounding scope, accept parameters, specify a return type, and contain a function body. Lambdas are commonly used with algorithms and other functions that accept callable objects.
Source Code #
#include <iostream>
int main()
{
auto add = [](int first, int second)
{
return first + second;
};
int result = add(10, 20);
std::cout << "Sum: " << result << '\n';
return 0;
}
Output #
Sum: 30
Explanation #
[]is the capture clause of the lambda expression.- An empty capture clause means that the lambda does not capture variables from the surrounding scope.
(int first, int second)defines the lambda’s parameters.- The statements enclosed within
{}form the lambda’s function body. return first + second;returns the sum of the two parameters.auto addstores the lambda in a variable using type deduction.add(10, 20)invokes the lambda with10and20as arguments.- The return type of the lambda is deduced automatically from its
returnstatement in this example. - Lambda expressions can be passed directly to functions that accept callable objects.
return 0;terminates the program successfully.