Skip to content
Learn Netverks

Lesson

Step 26/36 72% through track

lambdas-cpp

Lambdas

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Lambdas: the syntax, patterns, and safety habits you need before advancing in C++.

Teams still ship Lambdas in C++ codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Lambdas in contexts like: Game engines, trading systems, desktop apps, and performance-critical libraries.

Write C++ in main.cpp with int main(), click Run on server—the dev runner compiles with c++/g++ -std=c++17 -Wall and runs the binary; read template errors in stderr (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Lambda expressions create anonymous function objects inline—ideal for STL algorithms and short callbacks, similar in spirit to arrow functions in JavaScript.

Syntax

int factor = 2;
auto scale = [factor](int x) { return x * factor; };
std::cout << scale(21) << "\n";

Capture [=] by value, [&] by reference, or list specific names.

With algorithms

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

Important interview questions and answers

  1. Q: Capture gotcha?
    A: `[&]` referencing locals that die before the lambda runs causes dangling references—capture by value or ensure lifetime.
  2. Q: Generic lambda?
    A: C++14 auto parameters create templated call operator.

Self-check

  1. What does [&] capture?
  2. Where are lambdas commonly used in STL?

Pitfall: Lambdas capturing locals by reference ([&]) dangle if the lambda outlives the scope—capture by value for async callbacks.

Interview prep

[&] capture danger?

Capturing locals by reference in lambdas that outlive the scope causes dangling references.

Lambdas with STL?

Pass lambdas to sort, find_if, for_each, and other algorithms.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Capture [=]?
  • Mutable lambda?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump