• Home
  • 6.16 Lambda Functions

6.16 Lambda Functions

View Categories

6.16 Lambda Functions

1 min read

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 add stores the lambda in a variable using type deduction.
  • add(10, 20) invokes the lambda with 10 and 20 as arguments.
  • The return type of the lambda is deduced automatically from its return statement in this example.
  • Lambda expressions can be passed directly to functions that accept callable objects.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *