Back to C++
2026-02-275 min read

C++ Lambda

Learn C++ Lambda step by step with clear examples and exercises.

Why This Matters

Lambda functions are an essential part of modern C++ programming, offering numerous advantages that make code more concise, readable, and flexible. Here's a detailed look at why lambda functions matter:

  1. Simplified Code Structure: Lambda functions eliminate the need to define separate function definitions, reducing clutter and making your code cleaner and easier to maintain.
  2. Enhanced Readability: By reducing the number of global or named functions, lambda functions help improve the overall readability of your codebase.
  3. Flexibility: Lambda functions allow you to create functions on-the-fly based on specific requirements, making them ideal for situations where traditional function definitions might be overkill or too inflexible.
  4. Functional Programming Techniques: Lambda functions facilitate the use of functional programming techniques, making your code more concise and expressive by allowing you to work with higher-order functions and avoid unnecessary state.

Prerequisites

To fully understand and use lambda functions in C++, it is essential that you have a good grasp of the following concepts:

  1. Basic C++ syntax and control structures (if-else, loops, etc.)
  2. Function definitions and parameters
  3. Classes and objects
  4. Standard Template Library (STL) concepts such as vectors, iterators, and algorithms
  5. Understanding of function pointers and functors (for compatibility with older C++ compilers)

Core Concept

A lambda function is an unnamed function that can be created directly within the scope of another function or global namespace. The syntax for a lambda function consists of several components:

  1. Capture Clause: Defines the variables that the lambda function has access to from its surrounding context.
  2. Function Parameters: Specified using the same syntax as regular functions.
  3. Function Body: Contains the code to be executed by the lambda function.
  4. Return Type: Inferred based on the expression in the function body, or explicitly specified using ->.
  5. Attributes: Optional attributes that provide additional information about the lambda function, such as its thread safety and exception handling behavior.

Here's an example of a simple lambda function that takes two integers and returns their sum:

auto sum = [](int a, int b) -> int { return a + b; };

In this example, the capture clause is empty, the function parameters are a and b, and the function body consists of a single line that calculates the sum and returns it. The auto keyword tells the compiler to infer the return type based on the expression in the function body.

Worked Example

Let's consider a more complex example involving sorting a vector of integers using lambda functions:

#include <vector>
#include <algorithm>

int main() {
std::vector<int> numbers = {5, 3, 1, 4, 2};

// Sort the vector using a lambda function as the sorting criterion.
std::sort(numbers.begin(), numbers.end(), [](const int& a, const int& b) { return a < b; });

// Print the sorted vector.
for (const auto& number : numbers) {
std::cout << number << " ";
}

return 0;
}

In this example, we define a lambda function as the third argument to the std::sort algorithm from the STL. The lambda function takes two integer parameters (a and b) and returns true if a is less than b, effectively sorting the vector in ascending order.

Common Mistakes

  1. Forgetting to capture necessary variables: If a variable is used within the lambda function but not captured, it will not be accessible.
int x = 5;
auto lambda = [y = 3] { return x + y; }; // Correct: Captures and uses 'x' by value
auto incorrect_lambda = [] { return x + 3; }; // Incorrect: Does not capture or use 'x'
  1. Using the wrong capture mode: Lambda functions can be captured by value ([=]) or by reference ([&]). Capturing by value creates a copy of each captured variable, while capturing by reference allows modifications to the original variables from within the lambda function.
  2. Forgetting to return a value: If the lambda function does not explicitly return a value and there is no return statement in the function body, the compiler will generate an error.
  3. Incorrectly specifying capture clauses: Be mindful of capturing variables by copy or reference, and ensure that you only capture what is necessary to avoid unnecessary overhead.
  4. Ignoring lambda function attributes: Understanding the thread safety and exception handling behavior of your lambda functions can help prevent unexpected issues in multi-threaded programs.

Practice Questions

  1. Write a lambda function that takes two integers as parameters and returns their product.
  2. Given a vector of strings, write a lambda function to sort it alphabetically by length.
  3. Write a lambda function that takes a reference to an integer variable and increments its value each time it is called.
  4. Implement a lambda function that finds the maximum element in a given array using recursion.
  5. Write a lambda function that calculates the factorial of a given number.

FAQ

Q: Can I capture variables by copy, reference, or both in a lambda function?

A: Yes, you can capture variables by value ([=]), by reference ([&]), or a combination of both ([a,&b]).

Q: How does the compiler determine the return type of a lambda function when using auto?

A: The compiler infers the return type based on the expression in the function body, and you can specify an explicit return type using ->.

Q: Can I use lambda functions with older C++ compilers that do not support C++11 or later?

A: No, lambda functions are a feature introduced in C++11 and will not work with older compilers. You can use alternative techniques such as functors or function pointers for compatibility with older versions of C++.

Q: How does the capture clause affect the lifetime of captured variables?

A: Captured variables have their lifetimes extended to the lifetime of the lambda object if they are captured by value ([=]) or until the lambda object is destroyed if they are captured by reference ([&]).

Q: Can I use lambda functions for event handling in a GUI application?

A: Yes, lambda functions can be used for event handling in many modern GUI libraries, such as Qt and wxWidgets, providing a clean and concise way to handle user interactions.

C++ Lambda | C++ | XQA Learn