Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 26 Beginner

Lambda Expressions in C++

Updated: May 17, 2026
5 min read

# CHAPTER 26

Lambda Expressions

1. Introduction

Sometimes you need a tiny, throwaway function to do a very specific job just once (like sorting an array based on a custom rule). Writing a full function definition at the top of your file just for this one use is tedious. Lambda Expressions (introduced in C++11) allow you to write anonymous, unnamed functions directly inline exactly where you need them.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the syntax of a Lambda Expression.
  • Use the Capture Clause [] to access external variables.
  • Pass parameters () to a Lambda.
  • Define trailing return types ->.
  • Pass Lambdas to STL algorithms like std::sort.

3. Syntax of a Lambda

A lambda expression consists of three main parts, plus an optional return type.

Syntax: captureclause -> returntype { body };

cpp
1234567891011121314
#include <iostream>
using namespace std;

int main() {
    // A basic lambda that takes no parameters and captures nothing
    auto sayHello = []() {
        cout << "Hello from Lambda!" << endl;
    };
    
    // Call the lambda like a normal function
    sayHello();
    
    return 0;
}

4. Parameters and Return Types

Lambdas can take parameters just like regular functions. The return type is usually deduced automatically by the compiler, but you can specify it using the arrow ->.
cpp
123456789101112
// Lambda with parameters
auto add = [](int a, int b) {
    return a + b; // Compiler deduces return type is int
};

cout << add(5, 10) << endl; // Prints 15

// Lambda with an explicit return type
auto divide = [](double a, double b) -> double {
    if (b == 0) return 0.0;
    return a / b;
};

5. The Capture Clause []

Normal functions cannot access variables inside main(). Lambdas *can*, but you have to explicitly tell the lambda what variables to "capture".
  • [x] : Capture variable x by value (read-only copy).
  • [&x] : Capture variable x by reference (can modify the original).
  • [=] : Capture ALL external variables by value.
  • [&] : Capture ALL external variables by reference.
cpp
123456789101112131415161718192021
int main() {
    int multiplier = 5;
    
    // Capture 'multiplier' by value
    auto multiply = [multiplier](int num) {
        return num * multiplier;
    };
    
    cout << multiply(10) << endl; // Prints 50
    
    int score = 0;
    // Capture 'score' by reference so we can modify it
    auto scorePoint = [&score]() {
        score++;
    };
    
    scorePoint();
    cout << "Score is: " << score << endl; // Prints 1
    
    return 0;
}

6. Lambdas with STL Algorithms

Lambdas shine the brightest when used as arguments for STL algorithms.
cpp
123456789101112131415161718
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {4, 1, 3, 5, 2};
    
    // Sort descending using a lambda
    sort(v.begin(), v.end(), [](int a, int b) {
        return a > b; // Custom rule: a comes before b if a is greater
    });
    
    // Output: 5 4 3 2 1
    for (int num : v) { cout << num << " "; }
    
    return 0;
}

7. Memory-Level Explanation

Under the hood, a Lambda expression is not actually a function. The C++ compiler generates a hidden anonymous class (a Functor). The variables inside the capture clause [] become private member variables of that class, and the code inside the body {} goes into an overloaded operator() function.

8. Common Mistakes

  • Modifying captured-by-value variables: If you write [x]() { x++; }, the compiler throws an error because captured values are const (read-only) by default. You must either capture by reference [&x] or use the mutable keyword: [x]() mutable { x++; }.
  • Dangling References: Capturing by reference [&] in a lambda that outlives the scope of the variables it captured will cause memory corruption (just like a dangling pointer).

9. Exercises

  1. 1. Write a lambda expression that takes an integer and returns true if it is even, and false otherwise.
  1. 2. Create a vector of numbers. Use std::count_if with a lambda to count how many numbers in the vector are greater than 10.

10. MCQ Quiz with Answers

Question 1

What is a Lambda Expression in C++?

Question 2

Which brackets represent the Capture Clause?

Question 3

What does [&] mean in the capture clause?

Question 4

What is the correct syntax to specify a return type of float for a lambda?

Q5. Can a lambda expression take parameters? a) Yes, placed in the () b) No, they are parameterless Answer: a) Yes, placed in the ()
Question 6

If int x = 10;, what happens in auto f = [x]() { x++; };?

Question 7

What C++ feature actually powers lambdas behind the scenes?

Question 8

Why use Lambdas with STL functions like std::sort?

Q9. Is it mandatory to define a return type for a lambda? a) Yes b) No, the compiler usually deduces it from the return statement Answer: b) No, the compiler usually deduces it from the return statement

Q10. Can you assign a lambda to an auto variable and call it later? a) Yes b) No Answer: a) Yes

11. Interview Questions

  • Q: Explain what the mutable keyword does in a Lambda expression.
  • Q: Explain the hidden mechanics of a Lambda (how the compiler transforms it into a class/functor).
  • Q: What is the risk of capturing variables by reference [&] in a lambda that is stored and executed later?

12. Summary

Lambda expressions provide a concise way to define anonymous functions inline. Using the capture clause [], they can seamlessly access local variables. They are heavily used in Modern C++ alongside the STL to write clean, localized, and expressive code.

13. Next Chapter Recommendation

In Chapter 27: C++ Casts and Type Conversions, we will explore the safe, modern ways to convert data between types, moving away from dangerous C-style casts.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·