Skip to main content
Back to Blog
Programming Languages
14 August 20263 min readUpdated 14 August 2026

Understanding C++ Lambda Functions

C++ Lambda Functions Introduction to Lambda Functions A lambda function in C++ is a concise, unnamed function that you can define directly in your code. This feature is particul...

Understanding C++ Lambda Functions

C++ Lambda Functions

Introduction to Lambda Functions

A lambda function in C++ is a concise, unnamed function that you can define directly in your code. This feature is particularly useful for creating quick functions without the need for naming or declaring them separately. Think of it as a "function on the fly."

Basic Lambda Example

To illustrate, consider a lambda function stored in message, which simply outputs a message to the console.

#include <iostream>

int main() {
    auto message = []() {
        std::cout << "Hello World!" << std::endl;
    };
    message();
    return 0;
}

Lambda with Parameters

Just like a regular function, lambda functions can accept parameters. This allows you to pass values into them for processing.

Passing Lambdas to Functions

A lambda function can also be passed as an argument to another function. This is beneficial when you want to specify the action a function should perform, rather than just the data it should use. For example, you can pass a lambda to a function that executes it multiple times. Ensure you include the <functional> library for such operations.

Using Lambdas in Loops

Lambdas are particularly handy within loops, enabling you to define actions quickly and execute them repeatedly.

Capture Clause []

The [ ] brackets, known as the capture clause, allow a lambda to access variables from its surrounding scope. For instance, capturing a variable by value involves making a copy:

int x = 10;
auto lambda = [x]() {
    std::cout << "Captured value: " << x << std::endl;
};

Note that this captures a copy of x, so changes to x after the lambda's definition do not affect the lambda.

Capture by Reference

To ensure a lambda uses the most current value of a variable, you can capture it by reference using [&]. This means any changes to the variable will be reflected within the lambda, as it operates on the original variable:

int x = 10;
auto lambda = [&x]() {
    std::cout << "Captured reference: " << x << std::endl;
};

Regular Functions vs Lambda Functions

Both regular and lambda functions allow for code grouping and delayed execution, but they suit different scenarios.

Use a regular function when:

  • The function will be reused in various parts of the code.
  • A clear, descriptive name is important.
  • The function logic is lengthy or complex.

Use a lambda function when:

  • The function is needed only once.
  • The code is brief and straightforward.
  • You want to pass a function quickly to another function.

These examples illustrate both approaches, achieving the same result: returning the sum of two numbers.