Lambda syntax
- C++ course
- Intermediate
- Lesson 77/116
- 5 min
Learn the [](){} structure and capture clause.
Lambda syntax
The full lambda syntax is: [capture](parameters) -> return_type { body }. Each part is optional but the order is fixed. capture captures outer variables, parameters takes parameters, return_type sets the return type, body is the body.
The -> return_type is usually omitted; the compiler deduces the type from the return statement. For example [](int a, int b) { return a + b; } automatically deduces int as the return type. If multiple return statements return different types, an explicit return type is needed: [](int x) -> double { if (x) return x; return 0.0; }.
Return type deduction
The return type of a lambda is usually deduced automatically. If it sees return x * 2; it deduces int, if it sees return x > 0; it deduces bool. This is known as auto return type deduction.
Sometimes an explicit return type is needed: especially when different return statements return different types. Then you specify a return type like -> double: [](int x) -> double { return x / 2.0; }. This guarantees the lambda result is a double. Otherwise the compiler errors on conflicting return types.
Practice Write a two-parameter lambda
Define a two-parameter lambda with auto add = [](int a, int b) { return a + b; };. In main, print the result of add(3, 4) with std::cout.
Starter code
#include <iostream>
int main() {
// Define the add lambda and call it with 3, 4
return 0;
}Sample solution
#include <iostream>
int main() {
auto add = [](int a, int b) { return a + b; };
std::cout << add(3, 4);
return 0;
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the capture clause
auto f = ____(int x) { return x; };
auto f = [](int x) { return x; };
Explanation: An empty capture clause captures no variables.
2 What does [] specify in a lambda?
auto f = [](int x) { return x; };- Parameter list
- Return type
- Capture clause Correct answer
- Body
Explanation: [] is the capture clause; it captures outer variables.
3 Match each part to its role
| Term | Meaning |
|---|---|
[capture] |
Outer variable capture |
(parameters) |
Parameter list |
-> return_type |
Return type |
{ body } |
Body |