CPP: Lambda function
- Ashok Kumar Kumawat
- May 11
- 3 min read
What is a Lambda Function in C++?
A lambda function (often just called a "lambda") is an anonymous function—a function without a name. Introduced in C++11, lambdas allow you to write quick, throwaway functions directly inline inside your code, exactly where you need them.
They are incredibly useful when you need to pass a short snippet of code to another function, such as when using C++ Standard Library (STL) algorithms like std::sort, std::find_if, or std::for_each.
The Syntax of a Lambda
The general syntax of a C++ lambda looks like this:
[capture_list] (parameters) -> return_type {
// function body
}
Here is a breakdown of the parts:
[capture_list] (The Capture Clause): This is what makes lambdas special. It defines which variables from the surrounding scope the lambda is allowed to use inside its body.
(parameters): Just like a regular function, you can pass arguments to a lambda. (Optional if there are no parameters).
-> return_type: The type of value the lambda returns. (Optional; the compiler can almost always automatically deduce this, so you rarely need to write it).
{ body }: The actual code the lambda executes.
Understanding the Capture Clause []
Because a lambda is created inside another function, it often needs to access local variables from that function. The capture clause tells the compiler exactly how to bring those variables inside the lambda.
[] : Capture nothing. The lambda cannot use any variables from the outside scope.
[x, y] : Capture specific variables by value. The lambda gets a copy of x and y. It can read them, but modifying them won't affect the original variables.
[&x, &y] : Capture specific variables by reference. The lambda can read and modify the original x and y.
[=] : Capture everything by value. The lambda automatically makes a copy of any outside variable it uses.
[&] : Capture everything by reference. The lambda automatically gets a reference to any outside variable it uses.
Practical Examples
Example 1: A Basic Lambda
Here is the simplest form of a lambda. We assign it to a variable so we can call it.
#include <iostream>
int main() {
// Create a lambda and assign it to an 'auto' variable
auto sayHello = []() {
std::cout << "Hello from the lambda!" << std::endl;
};
// Call the lambda
sayHello();
return 0;
}
Example 2: Using Lambdas with STL Algorithms (Where they shine)
Before lambdas, if you wanted to sort a vector in a custom way, you had to write a separate function elsewhere in your file. Now, you can do it inline.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9};
// Use a lambda to sort in descending order
std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a > b; // Returns true if 'a' should come before 'b'
});
for (int n : numbers) std::cout << n << " "; // Output: 9 8 5 2 1
return 0;
}
Example 3: Capturing Variables
Here, we use an outside variable inside the lambda.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int multiplier = 10; // A local variable
// We capture 'multiplier' by value using [multiplier]
std::for_each(numbers.begin(), numbers.end(), [multiplier](int n) {
std::cout << n * multiplier << " ";
});
// Output: 10 20 30 40 50
return 0;
}
Why Use Lambdas?
Readability: The logic for a short operation is kept exactly where it is used, rather than hidden away in a helper function hundreds of lines away.
Less Boilerplate: You don't have to create entire structs or classes (functors) just to pass state into an algorithm.
Encapsulation: It keeps small, highly specific logic contained rather than cluttering your global namespace with tiny, single-use functions.
Comments