Lambda Captures in C++

Level 5544 keystrokes

Shows the lambda capture modes: [=] copies variables, [&] references them, a capture list can mix both, and an init capture with mutable creates state that the lambda keeps between calls.

C++ code

1int multiplier = 10;
2string prefix = "Result: ";
3
// [=] copies multiplier (10) and prefix when the lambda is created
4auto byValue = [=](int x) { return prefix + to_string(x * multiplier); };
// [&] refers to the original variables, so it can change multiplier
5auto byRef = [&](int x) { multiplier += x; return multiplier; };
// Mixed: multiplier by reference, prefix by value
6auto mixed = [&multiplier, prefix](int x) {
// Changes the original multiplier
7 multiplier *= x;
8 return prefix + to_string(multiplier);
9};
10
// Uses the copy taken earlier: 5 × 10, prints "Result: 50"
11cout << byValue(5) << endl;
// multiplier becomes 10 + 3 = 13
12cout << "After byRef(3): " << byRef(3) << endl;
// multiplier becomes 13 × 2 = 26: prints "Result: 26"
13cout << mixed(2) << endl;
14
// Init capture creates total inside the lambda; mutable allows changing it
15auto initCapture = [total = 0](int x) mutable { return total += x; };
// total is kept between calls: 5, then 8 (left-to-right order is guaranteed since C++17)
16cout << "Running total: " << initCapture(5) << ", " << initCapture(3) << endl;

Output

Result: 50
After byRef(3): 13
Result: 26
Running total: 5, 8
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 24
  • ;× 16
  • (× 12
  • )× 12
  • =× 11
  • "× 8
  • [× 4
  • ]× 4
  • {× 4
  • }× 4

More C++ examples at level 5

← C++ typing practice