codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

24 / 87 topics
18Function Basics & User-defined Types19Function Parameters20Inline Functions21Function Overloading22Scope23Recursion24Lambda Expressions
Tutorials/C++ Programming/Lambda Expressions
⚡C++ Programming

Lambda Expressions

Updated 2026-05-12
30 min read

Lambda Expressions

Introduction

In C++, lambda expressions provide a convenient way to define anonymous functions (functions without a name) directly in the code. They are particularly useful for short, throwaway functions that you don't need to reuse elsewhere. Lambda expressions enhance code readability and flexibility by allowing you to write inline functions tailored to specific contexts.

Lambda expressions are especially powerful when used with Standard Template Library (STL) algorithms, which often require function objects or callable entities as arguments. Understanding how to use lambda expressions effectively can significantly streamline your C++ programming.

Core Content

Lambda Syntax

A lambda expression in C++ consists of the following parts:

  1. Capture Clause: Specifies what variables from the enclosing scope are accessible inside the lambda.
  2. Parameter List: Lists any parameters that the lambda takes, similar to a regular function.
  3. Mutable Specification: Allows modifying captured variables by value.
  4. Exception Specification: Optional, specifies which exceptions the lambda can throw.
  5. Trailing Return Type: Specifies the return type of the lambda.
  6. Lambda Body: Contains the code that defines what the lambda does.

The basic syntax is:

C++
1[capture](parameters) -> return_type { body }

Example: Basic Lambda

basic_lambda.cpp
1#include <iostream>
2
3int main() {
4 auto greet = []() { std::cout << "Hello, World!
5"; };
6 greet();
7 return 0;
8}
Output
Hello, World!

Capture Clauses

By Value

Variables captured by value are copied into the lambda's scope.

Example: Capture by Value

capture_by_value.cpp
1#include <iostream>
2
3int main() {
4 int x = 10;
5 auto func = [x]() { std::cout << "Value of x: " << x << "
6"; };
7 func();
8 return 0;
9}
Output
Value of x: 10

By Reference

Variables captured by reference are accessible as references, allowing modification.

Example: Capture by Reference

capture_by_reference.cpp
1#include <iostream>
2
3int main() {
4 int x = 10;
5 auto func = [&x]() { std::cout << "Value of x before change: " << x << "
6";
7 x = 20;
8 std::cout << "Value of x after change: " << x << "
9"; };
10 func();
11 return 0;
12}
Output
Value of x before change: 10
Value of x after change: 20

Generalized Capture

You can capture all variables by value or reference using = and &.

Example: Generalized Capture

generalized_capture.cpp
1#include <iostream>
2
3int main() {
4 int x = 10, y = 20;
5 auto func1 = [=]() { std::cout << "Value of x and y by value: " << x << ", " << y << "
6"; };
7 auto func2 = [&]() { std::cout << "Value of x and y by reference: " << x << ", " << y << "
8"; };
9 func1();
10 func2();
11 return 0;
12}
Output
Value of x and y by value: 10, 20
Value of x and y by reference: 10, 20

Mutable Lambdas

By default, lambda expressions that capture variables by value do not allow modification of those variables. The mutable keyword allows this.

Example: Mutable Lambda

mutable_lambda.cpp
1#include <iostream>
2
3int main() {
4 int x = 10;
5 auto func = [x]() mutable { std::cout << "Value of x before change: " << x << "
6";
7 x = 20;
8 std::cout << "Value of x after change: " << x << "
9"; };
10 func();
11 return 0;
12}
Output
Value of x before change: 10
Value of x after change: 20

Generic Lambdas

C++14 introduced generic lambdas, which can deduce the types of their parameters automatically.

Example: Generic Lambda

generic_lambda.cpp
1#include <iostream>
2
3int main() {
4 auto add = [](auto a, auto b) { return a + b; };
5 std::cout << "Sum of 5 and 3: " << add(5, 3) << "
6";
7 std::cout << "Sum of 2.5 and 1.2: " << add(2.5, 1.2) << "
8";
9 return 0;
10}
Output
Sum of 5 and 3: 8
Sum of 2.5 and 1.2: 3.7

Use with STL Algorithms

Lambda expressions are frequently used with STL algorithms to perform operations on collections.

Example: Using Lambda with std::for_each

lambda_with_stl.cpp
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int main() {
6 std::vector<int> numbers = {1, 2, 3, 4, 5};
7 std::for_each(numbers.begin(), numbers.end(), [](int& n) { n *= 2; });
8 for (const auto& num : numbers) {
9 std::cout << num << " ";
10 }
11 return 0;
12}
Output
2 4 6 8 10

Practical Example

Let's create a program that sorts a vector of strings by their length using a lambda expression.

Example: Sorting Strings by Length

sort_strings.cpp
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int main() {
6 std::vector<std::string> words = {"apple", "banana", "cherry", "date"};
7 std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { return a.length() < b.length(); });
8 for (const auto& word : words) {
9 std::cout << word << " ";
10 }
11 return 0;
12}
Output
date apple cherry banana

Summary

ConceptDescription
Lambda Syntax[capture](parameters) -> return_type { body }
Capture ClausesBy value ([x]), by reference ([&x]), generalized capture ([=], [&])
Mutable LambdasAllows modification of captured variables by value
Generic LambdasDeduces parameter types automatically
Use with STLEnhances flexibility and readability when used with STL algorithms

What's Next?

Now that you've learned about lambda expressions, the next topic is Arrays (1D and Multidimensional). Arrays are fundamental data structures in C++ that allow you to store multiple elements of the same type in contiguous memory locations. Understanding arrays will help you build more complex data structures and algorithms.

Stay tuned for the next lesson!


PreviousRecursionNext Arrays (1D and Multidimensional)

Recommended Gear

RecursionArrays (1D and Multidimensional)