C++
Module 26: Lambda Expressions and Functional ProgrammingAdvanced50 min read

Lambda Expressions & Functional Programming in Modern C++

Complete Advanced guide to C++ Lambdas: syntax breakdown, capture lists, closure internals, mutable & generic lambdas, STL algorithms, callbacks, std::function, constexpr, Concepts, and best practices.

Key Takeaways & Core Concepts
  • Why `auto` is used: Every lambda expression has a unique, unnamed closure type generated by the compiler. You cannot write its type name explicitly, so auto deduces it at compile time with zero overhead.
  • Why it can be stored in a variable: The lambda evaluates to a temporary closure object (an instance of that unnamed class), which square stores by value.
  • How it is invoked: square(5) calls operator()(5) on the closure object, identical to a normal function call.
  • When a normal function is better: Use a named function when the logic is large, reused across multiple files, or needs a clear API signature in a header file.

1. Introduction to Lambda Expressions

A lambda expression (introduced in C++11) is an anonymous, inline function object that you can define directly at the point where it is invoked or passed as an argument—without needing to declare a separate named function or functor class elsewhere.

#### Why Were Lambdas Introduced in C++? Before C++11, passing custom logic to STL algorithms like std::sort, std::find_if, or std::for_each required either:

  1. 1
    Writing a free function far away from the call site (which cannot easily hold local state), or
  2. 2
    Writing a verbose functor struct with operator() and constructor boilerplate.

Lambdas solve this by letting you write concise, stateful, zero-overhead callable objects right where you use them, dramatically improving code locality and readability.

#### Traditional Function vs. Lambda Equivalent Traditional Named Function:

CPP Code Example
1#include <iostream>
2using namespace std;
3
4int square(int n) {
5 return n * n;
6}
7
8int main() {
9 cout << square(5); // Output: 25
10}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines

Lambda Equivalent:

CPP Code Example
1#include <iostream>
2using namespace std;
3
4int main() {
5 auto square = [](int n) {
6 return n * n;
7 };
8
9 cout << square(5); // Output: 25
10}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines

Key Observations:

  • Why `auto` is used: Every lambda expression has a unique, unnamed closure type generated by the compiler. You cannot write its type name explicitly, so auto deduces it at compile time with zero overhead.
  • Why it can be stored in a variable: The lambda evaluates to a temporary closure object (an instance of that unnamed class), which square stores by value.
  • How it is invoked: square(5) calls operator()(5) on the closure object, identical to a normal function call.
  • When a normal function is better: Use a named function when the logic is large, reused across multiple files, or needs a clear API signature in a header file.

---

1. STL Sort, Count & Erase-Remove with Lambdas
1#include <iostream>
2#include <vector>
3#include <algorithm>
4using namespace std;
5
6int main() {
7 vector<int> nums = {5, 2, 9, 1, 7, 4, 8};
8 sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; });
9 int evens = count_if(nums.begin(), nums.end(), [](int n) { return n % 2 == 0; });
10 nums.erase(remove_if(nums.begin(), nums.end(), [](int n) { return n % 2 != 0; }), nums.end());
11
12 cout << "Evens count: " << evens << "\nRemaining evens: ";
13 for (int n : nums) cout << n << " ";
14 return 0;
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: Sorts descending, counts even numbers, and removes odd numbers using the erase-remove idiom.

2. Complete Lambda Syntax Breakdown

The full syntax of a C++ lambda expression is:

CPP Code Example
1[capture](parameters) mutable noexcept -> return_type {
2 // body
3};
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
3 lines
  1. 1
    `[capture]` (Capture List): Specifies which variables from the enclosing scope are accessible inside the lambda body, and whether they are captured by value or by reference.
  2. 2
    `(parameters)` (Parameter List): Works like a normal function's parameter list (supports multiple parameters, const&, references, and C++14 auto generic parameters). Can be omitted if empty ([]{ return 42; }).
  3. 3
    `mutable` (Optional): By default, a lambda's operator() is const, meaning value-captured variables cannot be modified inside the body. Adding mutable removes const from operator(), allowing the lambda to modify its own captured copies.
  4. 4
    `noexcept` (Optional): Guarantees the lambda will not throw exceptions. If an exception escapes a noexcept lambda, std::terminate() is called immediately.
  5. 5
    `-> return_type` (Optional Trailing Return Type): Usually deduced automatically from return statements, but required when multiple return statements return different compatible types (e.g., int and double).
  6. 6
    `{ body }` (Lambda Body): Contains any valid C++ statements—local variables, loops, conditionals, and return statements.

#### 5 Examples of Different Lambda Structures

CPP Code Example
1#include <iostream>
2using namespace std;
3
4int main() {
5 // 1. Minimal lambda (no params, no capture)
6 auto hello = [] { cout << "Hello C++\n"; };
7 hello();
8
9 // 2. Parameters + implicit return deduction
10 auto multiply = [](int a, int b) { return a * b; };
11 cout << multiply(4, 5) << "\n";
12
13 // 3. Explicit trailing return type
14 auto safeDiv = [](int a, int b) -> double {
15 if (b == 0) return 0.0;
16 return static_cast<double>(a) / b;
17 };
18 cout << safeDiv(7, 2) << "\n";
19
20 // 4. noexcept lambda
21 auto fastAdd = [](int a, int b) noexcept { return a + b; };
22 cout << fastAdd(10, 20) << "\n";
23
24 // 5. Mutable value-capture lambda
25 int count = 0;
26 auto ticker = [count]() mutable { return ++count; };
27 cout << ticker() << " " << ticker() << " (orig: " << count << ")\n";
28 return 0;
29}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
29 lines

Expected Output:

TEXT Code Example
1Hello C++
220
33.5
430
51 2 (orig: 0)
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
5 lines

---

2. Mutable Value-Capture Counter & Init-Capture Move (C++14)
1#include <iostream>
2#include <memory>
3using namespace std;
4
5int main() {
6 int count = 0;
7 auto counter = [count]() mutable { return ++count; };
8 cout << "Counter: " << counter() << ", " << counter() << " (orig: " << count << ")\n";
9
10 auto ptr = make_unique<int>(100);
11 auto reader = [p = move(ptr)]() { return *p; };
12 cout << "Moved unique_ptr value: " << reader() << "\n";
13 return 0;
14}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
14 lines
Note: `mutable` modifies the lambda's internal copy without affecting `count`; init-capture moves `unique_ptr` ownership.

3. Stateless Lambdas (Without Captures)

A lambda with an empty capture list `[]` is called a stateless lambda.

  • It cannot access local variables from the enclosing function unless passed as parameters.
  • It can access global variables, static variables, and constexpr constants directly.
  • Function Pointer Conversion: Because it holds no state, a non-capturing lambda can implicitly convert to a regular C/C++ function pointer with a matching signature!
CPP Code Example
1#include <iostream>
2using namespace std;
3
4int main() {
5 auto greet = []() { cout << "Hello C++\n"; };
6 auto add = [](int a, int b) { return a + b; };
7 auto isEven = [](int n) { return n % 2 == 0; };
8
9 // Implicit conversion to function pointer:
10 int (*fnPtr)(int, int) = add;
11 greet();
12 cout << "fnPtr(3, 4) = " << fnPtr(3, 4) << ", isEven(6) = " << isEven(6) << "\n";
13 return 0;
14}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
14 lines

---

3. Generic Lambda (C++14), std::function & Custom Student Sort
1#include <iostream>
2#include <vector>
3#include <string>
4#include <algorithm>
5#include <functional>
6using namespace std;
7
8struct Student { string name; int marks; };
9
10int main() {
11 auto add = [](auto a, auto b) { return a + b; };
12 cout << "Generic add: " << add(10, 20) << " | " << add(string("Code"), string("Zov")) << "\n";
13
14 function<int(int, int)> op = [](int x, int y) { return x * y; };
15 cout << "std::function op(6, 7): " << op(6, 7) << "\n";
16
17 vector<Student> s = {{"Aarav", 88}, {"Diya", 95}, {"Kabir", 76}};
18 sort(s.begin(), s.end(), [](const Student& a, const Student& b) { return a.marks > b.marks; });
19 cout << "Topper: " << s[0].name << " (" << s[0].marks << ")\n";
20 return 0;
21}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
21 lines
Note: Demonstrates C++14 generic `auto` lambda, `std::function` type erasure, and sorting custom objects.

4. Capture Lists – Deep Theory & Memory Model

The capture list controls what external state a lambda closes over and how it is stored inside the closure object.

#### 4.1 Capture by Value [x]

CPP Code Example
1int x = 10;
2auto show = [x]() { std::cout << x; };
3x = 99;
4show(); // Prints 10!
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
4 lines
  • What & When: A copy of x is made at the moment the lambda is defined (not when it is called).
  • Memory & Lifetime: The copy lives inside the closure object itself. Even if the original x changes later or goes out of scope, the lambda's copy remains 10.

#### 4.2 Capture by Reference [&x]

CPP Code Example
1int x = 10;
2auto show = [&x]() { x += 5; std::cout << x; };
3show(); // Prints 15, and outside x is now 15!
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
3 lines
  • Behavior: The closure stores a reference/pointer to the original x. Modifications inside the lambda mutate the caller's x.
  • Dangling Reference Risk: If the lambda outlives x (e.g., returned from a function or sent to a detached thread), calling it triggers Undefined Behavior!

#### 4.3 Default Value Capture [=] & Default Reference Capture [&]

  • [=]: Captures all odr-used local variables by value. Convenient, but can accidentally copy large objects or this.
  • [&]: Captures all odr-used local variables by reference. Safe only when the lambda executes synchronously within the same scope (e.g., std::sort).

#### 4.4 Mixed Captures [x, &y] & [=, &y] / [&, x] You can mix modes selectively: [x, &y] copies x and references y, improving readability and safety by making mutations explicit.

#### 4.5 Capture Initializers / Init-Capture (C++14) Init-capture lets you create new member variables inside the closure, rename captures, or move non-copyable objects like std::unique_ptr into a lambda:

CPP Code Example
1#include <iostream>
2#include <memory>
3
4int main() {
5 auto ptr = std::make_unique<int>(100);
6 auto lambda = [p = std::move(ptr)]() {
7 return *p;
8 };
9 std::cout << "Moved value: " << lambda() << "\n";
10 // ptr is now nullptr! Ownership belongs exclusively to lambda.
11 return 0;
12}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines

---

5. Lambda Closure Objects & Internal Working

When the compiler sees a lambda, it generates an unnamed functor class (a closure type) and instantiates a closure object.

CPP Code Example
1int multiplier = 5;
2auto multiply = [multiplier](int value) {
3 return multiplier * value;
4};
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
4 lines

Conceptual Compiler-Generated Equivalent:

CPP Code Example
1class __UnnamedLambda {
2private:
3 int multiplier; // Captured state becomes private data members
4public:
5 __UnnamedLambda(int value) : multiplier(value) {}
6
7 // Call operator is const by default!
8 int operator()(int value) const {
9 return multiplier * value;
10 }
11};
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
11 lines

(Note: This is a conceptual model of how a capturing lambda behaves, not the exact compiler-generated internal symbol.)

  • Stateless vs. Stateful: A stateless lambda has no data members (size 1 byte, empty class) and converts to a function pointer. A stateful lambda stores its captured members and cannot convert to a plain C function pointer.

---

6. Mutable Lambdas

Because operator() is const by default, modifying a value-captured variable fails to compile unless you add mutable:

CPP Code Example
1#include <iostream>
2using namespace std;
3
4int main() {
5 int count = 0;
6 auto increment = [count]() mutable {
7 ++count;
8 cout << count << " ";
9 };
10 increment(); // 1
11 increment(); // 2
12 increment(); // 3
13 cout << "| Original count = " << count << "\n"; // 0
14 return 0;
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines

Output: 1 2 3 | Original count = 0

FeatureNormal Value CaptureMutable Value Capture
Definition[x]() { ... }[x]() mutable { ... }
Captured copyYesYes
Modify captured copyNo (operator() is const)Yes (operator() is non-const)
Modify original variableNoNo (unless separately captured by &)
Stateful across callsNoYes (each closure object has its own state)

---

7. Generic Lambdas (C++14) & C++20 Template Lambdas

In C++14, using auto in a lambda parameter turns operator() into a member function template!

CPP Code Example
1#include <iostream>
2#include <string>
3using namespace std;
4
5int main() {
6 auto add = [](auto a, auto b) { return a + b; };
7 auto greater = [](auto a, auto b) { return a > b; };
8 auto display = [](const auto& val) { cout << val << "\n"; };
9
10 display(add(10, 20));
11 display(add(2.5, 3.5));
12 display(add(string("Hello "), string("C++")));
13 display(greater(50, 25));
14 return 0;
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines

In C++20, you can also use explicit template syntax and Concepts to constrain types:

CPP Code Example
1#include <concepts>
2auto addInts = []<typename T>(T a, T b) requires std::integral<T> {
3 return a + b;
4};
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
4 lines

---

8. Return Types & Deduction Rules

  • Single or consistent returns: Deduced automatically ([](double a, double b) { return a / b; } -> double).
  • Multiple returns with different types: [](bool flag) { if (flag) return 1; return 2.5; } is a compile error unless you specify -> double.
  • No return statement: Deduced as void.

---

9. Lambdas with STL Algorithms

Lambdas make STL algorithms (<algorithm>) expressive and fast (inlined by the compiler):

CPP Code Example
1#include <iostream>
2#include <vector>
3#include <algorithm>
4using namespace std;
5
6int main() {
7 vector<int> nums = {5, 2, 9, 1, 7, 4, 8};
8
9 // 1. Sort descending
10 sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; });
11
12 // 2. Count even numbers
13 int evens = count_if(nums.begin(), nums.end(), [](int n) { return n % 2 == 0; });
14
15 // 3. Find first element < 5
16 auto it = find_if(nums.begin(), nums.end(), [](int n) { return n < 5; });
17
18 // 4. Transform into squares
19 vector<int> squares(nums.size());
20 transform(nums.begin(), nums.end(), squares.begin(), [](int n) { return n * n; });
21
22 // 5. Erase-Remove Idiom (remove odd numbers)
23 nums.erase(remove_if(nums.begin(), nums.end(), [](int n) { return n % 2 != 0; }), nums.end());
24
25 cout << "Evens count: " << evens << "\n";
26 if (it != nums.end()) cout << "First < 5: " << *it << "\n";
27 cout << "Remaining evens: ";
28 for (int n : nums) cout << n << " ";
29 return 0;
30}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
30 lines

Also useful: std::for_each, std::all_of, std::any_of, and std::none_of.

---

10. Lambdas as Callbacks, Function Pointers & `std::function`

  • Template Callback (C++11/14/17): Zero overhead, inlined!
CPP Code Example
1 template <typename Fn>
2 void process(int value, Fn callback) { callback(value); }
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
2 lines
  • Abbreviated Template Callback (C++20): void process(int value, auto callback) { callback(value); }
  • `std::function<R(Args...)>` (`<functional>`): A type-erased polymorphic wrapper that can store any callable (stateless lambda, capturing lambda, functor, or function pointer). Use std::function only when you need to store heterogeneous callables in a container or cross an ABI/interface boundary—otherwise prefer auto or templates to avoid heap/virtual-call overhead.
Callable TypeCan Hold State?Type-Erased?OverheadBest Use Case
Normal FunctionNoNoZeroReusable named logic
Function PointerNoPartially (signature)Indirect callC APIs, callbacks
Functor (Class)YesNoZero (inlined)Complex reusable stateful objects
Lambda (`auto`)YesNoZero (inlined)Inline STL predicates, callbacks
`std::function`YesYesSmall (virtual/heap)Heterogeneous callback storage

---

11. Lambdas with Containers & Custom Objects

CPP Code Example
1#include <iostream>
2#include <vector>
3#include <string>
4#include <algorithm>
5using namespace std;
6
7struct Student {
8 string name;
9 int marks;
10};
11
12int main() {
13 vector<Student> students = {{"Aarav", 88}, {"Diya", 95}, {"Kabir", 76}};
14
15 // Sort by marks descending
16 sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
17 return a.marks > b.marks;
18 });
19
20 // Find first student above 90
21 auto top = find_if(students.begin(), students.end(), [](const Student& s) {
22 return s.marks > 90;
23 });
24
25 if (top != students.end()) {
26 cout << "Topper: " << top->name << " (" << top->marks << ")\n";
27 }
28 return 0;
29}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
29 lines

---

12. Functional Programming, `constexpr` Lambdas & Threading

  • Functional Programming Concepts: C++ is multi-paradigm; lambdas bring first-class functions, higher-order functions (functions taking/returning lambdas), pure functions (no side effects), predicates, and function composition.
  • `constexpr` Lambdas (C++17+): Lambdas are implicitly constexpr if their body qualifies, enabling compile-time static_assert:
CPP Code Example
1 constexpr auto sq = [](int x) { return x * x; };
2 static_assert(sq(5) == 25);
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
2 lines
  • Threading & Lifetime Warning: When passing a lambda to std::thread or async tasks, prefer value captures `[=]` / `[x]` or std::shared_ptr over [&] unless you strictly join() before local variables go out of scope. Capturing a local variable by reference for a detached thread causes dangling-reference Undefined Behavior!

---

13. Common Lambda Mistakes & Best Practices

  1. 1
    Dangling reference capture `[&]`: Returning a lambda that captures a local variable by reference. Fix: Capture by value [x] or move with init-capture.
  2. 2
    Assuming `mutable` modifies the outer variable: mutable only modifies the closure's internal copy. Fix: Use [&x] if you intend to mutate the caller's variable.
  3. 3
    Comparator violating Strict Weak Ordering: Using <= instead of < in std::sort causes undefined behavior / crashes. Fix: Always use strict < or >.
  4. 4
    Missing `->` on mixed return types: Returning int in one branch and double in another. Fix: Add -> double.
  5. 5
    Overusing `std::function`: Paying type-erasure overhead where auto or a template parameter works at zero cost.

Best Practices:

  • Keep lambdas short, readable, and single-purpose.
  • Prefer explicit captures ([x, &y]) over [=] or [&] in non-trivial scopes.
  • Use const auto& in generic lambdas to avoid unnecessary copies.
  • Use named functions when logic exceeds ~10–15 lines or is reused widely.

---

14. 15 Practical Examples & Key Takeaways

From simple greetings and predicates (isEven, isPositive, maxOf) to std::sort, count_if, find_if, transform, Student sorting, mutable counters, and C++14 generic lambdas—lambdas are the backbone of Modern C++.

Key Takeaways:

  • Lambdas are syntactic sugar for compiler-generated closure objects with operator().
  • Empty [] lambdas are stateless and convert to function pointers.
  • [x] copies at creation; [&x] aliases the original; [p = std::move(ptr)] transfers ownership (C++14).
  • mutable unlocks modification of value-captured copies.
  • auto parameters (C++14) and <typename T> requires ... (C++20) enable generic lambdas.
Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)