Lambda capture in C++

Level 4207 keystrokes

One lambda captures multiplier by value to compute 5 * 3 = 15; another captures total by reference and adds to it, so total becomes 30.

C++ code

1int multiplier = 3;
// [multiplier] copies the value 3 into the lambda when it is created
2auto times = [multiplier](int n) { return n * multiplier; };
// 5 * 3: prints 15
3cout << times(5) << endl;
4
5int total = 0;
// [&total] refers to the outer total, so the lambda can modify it
6auto add = [&total](int n) { total += n; };
// Each call adds to the real total: 10, then 30
7add(10);
8add(20);
// Prints 30
9cout << total << endl;

Output

15
30
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.

  • ;× 10
  • <× 8
  • (× 5
  • )× 5
  • =× 5
  • [× 2
  • ]× 2
  • {× 2
  • }× 2
  • *× 1

More C++ examples at level 4

← C++ typing practice