A lambda function, or simply "lambda", is an anonymous (unnamed) function that is defined in place, within your source code, and with a concise syntax. Lambda functions were introduced in C++11 and have since become a widely used feature, especially in combination with the Standard Library algorithms.
Here is a basic syntax of a lambda function in C++:
[capture-list](parameters) -> return_type {
// function body
};
Here are a few examples to demonstrate the use of lambda functions in C++:
auto printHello = []() {
std::cout << "Hello, World!\n";
};
printHello(); // Output: Hello, World!
auto add = [](int a, int b) {
return a + b;
};
int result = add(3, 4); // result = 7
int multiplier = 3;
auto times = [multiplier](int a) {
return a * multiplier;
};
int result = times(5); // result = 15
int expiresInDays = 45;
auto updateDays = [&expiresInDays](int newDays) {
expiresInDays = newDays;
};
updateDays(30); // expiresInDays = 30
Note that, when using the capture by reference, any change made to the captured variable inside the lambda function will affect its value in the surrounding scope.
Visit the following resources to learn more: