How to Use Lambda in C++: Syntax and Examples
In C++, a
lambda is an anonymous function you can define inline using the syntax [capture](parameters) { body }. You use lambdas to write short, unnamed functions for quick tasks like sorting or callbacks.Syntax
A lambda expression in C++ has this basic form:
- [capture]: Specifies which outside variables the lambda can use.
- (parameters): The input parameters like a normal function.
- { body }: The code the lambda runs.
The capture can be empty [] if no outside variables are needed.
cpp
[capture](parameters) { body }Example
This example shows a lambda that adds two numbers and prints the result. It demonstrates defining, calling, and capturing variables.
cpp
#include <iostream> int main() { int x = 5; int y = 10; // Lambda that captures x and y by value and adds them auto add = [x, y]() { return x + y; }; std::cout << "Sum: " << add() << std::endl; // Lambda with parameters auto multiply = [](int a, int b) { return a * b; }; std::cout << "Product: " << multiply(3, 4) << std::endl; return 0; }
Output
Sum: 15
Product: 12
Common Pitfalls
Common mistakes when using lambdas include:
- Forgetting to capture variables needed inside the lambda.
- Capturing by value when you need to modify the original variable (use capture by reference).
- Using incorrect capture syntax.
Here is an example showing a wrong and right way to capture a variable:
cpp
#include <iostream> int main() { int count = 0; // Wrong: captures count by value, so increment inside lambda won't affect original auto wrong_lambda = [count]() mutable { count++; std::cout << "Inside wrong_lambda: " << count << std::endl; }; wrong_lambda(); std::cout << "Outside after wrong_lambda: " << count << std::endl; // Right: capture count by reference to modify original auto right_lambda = [&count]() { count++; std::cout << "Inside right_lambda: " << count << std::endl; }; right_lambda(); std::cout << "Outside after right_lambda: " << count << std::endl; return 0; }
Output
Inside wrong_lambda: 1
Outside after wrong_lambda: 0
Inside right_lambda: 1
Outside after right_lambda: 1
Quick Reference
Remember these tips when using lambdas in C++:
- Capture list: Use
[]for no capture,[&]to capture all by reference,[=]to capture all by value. - Mutable lambdas: Add
mutableafter parameters if you want to modify captured values by value. - Return type: Usually inferred, but specify with
-> typeif needed.
Key Takeaways
Lambdas are anonymous functions defined inline with syntax [capture](parameters) { body }.
Use capture lists to access outside variables inside lambdas.
Capture by reference to modify external variables, or by value to keep copies.
Mutable lambdas allow modifying captured variables when captured by value.
Lambdas are useful for short, quick functions like callbacks or algorithms.