What are lambdas?
- C++ course
- Intermediate
- Lesson 76/116
- 5 min
Learn what lambda expressions are and anonymous functions.
What are lambdas?
A lambda is an anonymous function. It is defined where it is used; no separate function declaration is needed. Example: [](int x) { return x * 2; }. This lambda takes an int and returns double its value.
Lambdas are usually assigned to a variable with auto: auto doubleIt = [](int x) { return x * 2; };. Then it is called like a normal function: doubleIt(5) gives 10. Lambdas are especially handy for passing small operations to STL algorithms; they remove the overhead of writing a separate function.
Lambda and function
A lambda works like a normal function but with differences. A normal function is named at compile time and can be called from other places. A lambda is usually defined where it is used and has no name; it can be assigned to a variable with auto.
The power of a lambda is that it can capture surrounding variables. This is something normal functions cannot do. For example in [](int x) { return x + offset; } the offset can come from the outer scope; the lambda captures it via the capture clause. We will cover this in later lessons.
Practice Define and call a lambda
Define a lambda with auto doubleIt = [](int x) { return x * 2; };. In main, print the result of doubleIt(5) with std::cout.
Starter code
#include <iostream>
int main() {
// Define the doubleIt lambda and call it with 5
return 0;
}Sample solution
#include <iostream>
int main() {
auto doubleIt = [](int x) { return x * 2; };
std::cout << doubleIt(5);
return 0;
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid lambda expression?
// valid lambda syntax- function(x) { return x; }
- [](int x) { return x; } Correct answer
- lambda(x) => x
- (int x) -> x
Explanation: [](int x) { return x; } is a valid lambda.
2 Complete the lambda body
auto doubleIt = [](int x) { return x ____; };
auto doubleIt = [](int x) { return x * 2; };
Explanation: Write * 2: return x * 2; doubles the value.
3 Match each piece to its role
| Term | Meaning |
|---|---|
[] |
Capture clause |
(int x) |
Parameter list |
{ return x; } |
Body |
auto f = [](...) {...}; |
Assignment |