Introduced in C++11, Lambda Expressions (often just called "lambdas") are a convenient way to define inline, anonymous functions right where you need them.
Instead of creating a separate, named function outside of main(), you can write a short, throwaway function on the fly. Lambdas are heavily used in modern C++, especially with algorithms like std::sort or std::for_each.
The basic structure of a lambda expression looks a bit strange at first, but it is highly logical once you understand its parts:
capture_clause -> return_type {
// Function body
};
[] (Capture Clause): Defines which variables from the surrounding scope are available inside the lambda.() (Parameters): Works exactly like regular function parameters.-> return_type: (Optional) Explicitly defines the return type. Most of the time, the compiler can guess this automatically.{} (Body): The actual code to execute.Let's create a lambda that prints a greeting and store it in a variable.
#include <iostream> using namespace std;int main() { // Define a lambda and store it in a variable named 'greet' auto greet = { cout << "Hello from a lambda!" << "\n"; };
// Call the lambda greet();
return 0; }
Note: We use the auto keyword because the exact type of a lambda is generated uniquely by the compiler and is too complex to write manually.
Lambdas can take inputs just like normal functions.
#include <iostream> using namespace std;int main() { // A lambda that adds two numbers and returns the result auto add = [](int a, int b) { return a + b; };
cout << "5 + 7 = " << add(5, 7) << "\n"; return 0; }
Normal functions cannot access variables inside main() unless you pass them as parameters. Lambdas are special—they can "capture" variables from their surrounding scope!
[x] captures the variable x by value (read-only copy).[&x] captures the variable x by reference (allows modification).[=] captures all outside variables by value.[&] captures all outside variables by reference.#include <iostream> using namespace std;int main() { int multiplier = 10;
// Capture 'multiplier' by value so we can use it inside auto multiply = [multiplier](int num) { return num * multiplier; };
cout << "3 times 10 is: " << multiply(3) << "\n"; return 0; }
Lambdas make C++ coding faster, more localized, and significantly more expressive!
What part of a lambda expression allows it to access variables from its surrounding scope?