“Know how to solve every problem that has been solved.” “What I cannot create, I do not understand.” — Richard Feynman

Lambdas: functions that carry state

Learn

Lesson 5 of 7 standard ~5 min

A lambda is an anonymous function you can define inline — but the interesting part is the capture: a lambda can close over variables from its surrounding scope, carrying them along as state. How it captures them (by value or by reference) is the whole game.

int x = 1;
auto byVal = [x]()  { return x; };  // copies x now
auto byRef = [&x]() { return x; };  // aliases x
Capture by value [x] vs by reference [&x].

Predict the difference capture mode makes.

standardPredict + reveal

What does this print? Look closely at how n is captured.

int n = 10;
auto f = [n]() { return n + 1; };
n = 100;
std::cout << f();
Go deeper ↓Lambdas in C++

Once you see that a lambda stores its captures, the question "what is a lambda, really?" has an obvious answer.

standardMultiple choice

Under the hood, what is a C++ lambda expression?

Go deeper ↓Lambdas in C++