Lambda functions have revolutionized the way developers write concise and efficient code in Modern C++. Introduced in C++11 and further enhanced in later versions, lambda functions allow for inline, anonymous function-like expressions, making them perfect for functional programming, callbacks, and algorithm manipulation.
In this blog, we’ll explore what lambda functions are, their syntax, key features, and benefits, along with practical examples to demonstrate their power. Whether you’re optimizing algorithms or simplifying function calls, lambda functions can significantly enhance your coding efficiency.
Modern C++ makes tremendous use of lambda functions which became available in C++11 and improved through later updates. Using Lambda functions inside your code lets you create and work with function-like entities in short direct expressions for better and faster programming.
A lambda function works as an unnamed function you can create directly in your code without using external declarations. Using captured scope variables makes lambda functions valuable for functional programming methods and algorithms plus callback handling.
[capture_clause](parameter_list) -> return_type {
// Function body
};
Example:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> num = {1, 2, 3, 4, 5};
// Lambda function to print each number
auto print = [](int n) { std::cout << n << ” “; };
std::for_each(num.begin(), num.end(), print);
return 0;
}
Output:
1 2 3 4 5
Capture Clause:
Indian Institute of Embedded Systems – IIES