🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C++ Lambda Expressions — Complete Beginner Guide

C++ FundamentalsC++ Lambda Expressions and Capture Modes🟢 Free Lesson

C++ Lambda Expressions — Complete Beginner Guide

Learning Objectives

  • Read and write lambda syntax step by step
  • Capture local values by value or reference
  • Choose safe default capture modes
  • Pass lambdas into algorithms and callbacks

A Function Without a Separate Name

A lambda is an inline function object you define right where it is needed. It keeps short logic close to its use site, which is ideal for sorting rules, filters, and event handlers.

#include <iostream>

int main() {
    auto greet = []() {
        std::cout << "hi from lambda" << std::endl;
    };

    greet();
    return 0;
}

Anatomy of A Lambda

PartExampleMeaning
capture listsquare bracketsWhat outer names are visible
parametersparenthesesInputs like a normal function
trailing returnminus greater than typeOptional result type
bodybracesSteps that run

When the body is a single return expression, the compiler often deduces the result type for you.

auto add = [](int a, int b) {
    return a + b;
};

For clarity on multi step bodies, write the return type explicitly after the parameter list.

Capture By Value

Capturing by value copies the outer variable into the lambda. Later changes outside do not affect the copy.

int factor = 3;
auto scale = [factor](int n) {
    return n * factor;
};
ModeSyntaxEffect
By valuename in bracketsSnapshot copy
By referenceampersand nameLive connection
Thisthis pointer formMember access for classes

Capture By Reference

Reference capture shares the outer variable. Mutations inside the lambda can be seen outside.

int total = 0;
auto accumulate = [&total](int n) {
    total += n;
};

Danger alert: never let a reference captured lambda outlive the variable it points at. Dangling references produce undefined behavior.

Default Captures

Default modes grab unspecified names automatically.

int a = 5;
int b = 7;

auto sumA = [=]() { return a; };       // copy all used by value
auto addB = [&]() { return a + b; };   // reference all used
DefaultMeaning
empty bracketsCapture nothing
equals sign in bracketsCopy all omissions by value
ampersand in bracketsReference all omissions
mixed listsExplicit overrides of the default

Prefer explicit captures in shared codebases. They document intent and reduce surprise writes.

Init Capture and Moving

Modern C plus plus allows capturing by moving a local into the lambda storage. This is helpful for unique ownership objects that cannot be copied.

auto owner = std::make_unique<int>(1);
auto useIt = [ptr = std::move(owner)]() {
    if (ptr) return *ptr;
    return 0;
};

You still see raw pointers and references in many examples; unique style capture closes the ownership story cleanly.

Lambdas With Standard Algorithms

This is the most common day to day use.

#include <algorithm>
#include <vector>
#include <iostream>

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

    int evens = static_cast<int>(
        std::count_if(nums.begin(), nums.end(),
                      [](int n) { return n % 2 == 0; }));

    std::sort(nums.begin(), nums.end(),
              [](int a, int b) { return a > b; });

    std::cout << evens << std::endl;
    return 0;
}

In source code the greater than symbol is used for descending order. Each lambda is a tiny policy injected into a generic algorithm.

Mutable Lambdas

By default, value captures are const inside the lambda body. The mutable keyword allows modifying copies without affecting outer variables.

int seed = 10;
auto copy = [seed]() mutable {
    seed += 1; // changes only the captured copy
    return seed;
};

Use mutable sparingly and only when local copy state is intentional.

Storing Lambdas

auto hides the long type name generated for each lambda. When you must store different lambdas together, a std::function wrapper can help at the cost of a little overhead.

#include <functional>

std::function<int(int, int)> op = [](int a, int b) {
    return a + b;
};

Common Mistakes

MistakeResult
Reference capturing a temporaryDangling reference risk
Default reference capture in large codeHidden dependencies
Assuming value capture updates outerCopies do not sync back
Heavy logic in one giant lambdaExtract a named function
Forgetting const on shared stateUnexpected mutation confusion

A Practical Example

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> names = {"ann", "bea", "cy", "dan"};
    int minLen = 3;

    auto shortNames = [minLen](const std::string& s) {
        return s.length() static_cast_less minLen;
    };

    names.erase(
        std::remove_if(names.begin(), names.end(),
                       [minLen](const std::string& s) {
                           return s.length() < minLen;
                       }),
        names.end());

    for (const auto& n : names) {
        std::cout << n << std::endl;
    }
    return 0;
}

The helper predicate in remove_if keeps the erase pattern clean. Compare lengths with the normal less than operator inside the lambda body.

Key Takeaways

💡

  • Lambdas are inline function objects with a capture list
  • Value captures snapshot; reference captures share live state
  • Prefer explicit captures over broad defaults in shared code
  • Main real world use is plugging logic into STL algorithms
  • Never return a lambda that references expired locals

Practice Questions

  1. Write a lambda that returns true for numbers greater than ten.
  2. What is the difference between empty brackets and equals sign brackets?
  3. When would you mark a lambda mutable?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C++ Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement