C++ Lambda

C++ Lambda Expressions: Anonymous Functions

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.


1. Syntax of a Lambda

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
};

2. A Simple Lambda Example

Let's create a lambda that prints a greeting and store it in a variable.

Basic Lambda Example

#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.


3. Lambdas with Parameters

Lambdas can take inputs just like normal functions.

Lambda with Parameters

#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; }


4. The Capture Clause (Accessing Outside Variables)

Normal functions cannot access variables inside main() unless you pass them as parameters. Lambdas are special—they can "capture" variables from their surrounding scope!

Lambda Capture Example

#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!


Exercise

?

What part of a lambda expression allows it to access variables from its surrounding scope?