Jaskamal Kainth

Lambda Expressions in C++

Lambda expressions were introduced in C++11 and provide a concise way to create anonymous function objects.

Basic Syntax

The basic syntax of a lambda expression is:

[capture-list](parameter-list) -> return-type { function-body }

Where:

Examples

Simple Lambda

auto add = [](int a, int b) { return a + b; };
std::cout << add(5, 3); // Outputs: 8

Capturing Variables

int multiplier = 5;
auto multiply = [multiplier](int x) { return x * multiplier; };
std::cout << multiply(3); // Outputs: 15

Mutable Lambda

By default, variables captured by value cannot be modified. Use the mutable keyword to allow modification:

int counter = 0;
auto increment = [counter]() mutable { return ++counter; };
std::cout << increment(); // Outputs: 1
std::cout << counter;     // Outputs: 0 (original not modified)

Lambda expressions are commonly used with algorithms from the standard library, such as std::sort, std::for_each, and std::transform.