← Back to C++ Course | Chapter 5: Functions | Lesson 11 of 13

C++ Lambda Functions

Basic Lambda Syntax

A lambda is a small, unnamed function you can define right where you need it, inside an expression, using the syntax [](parameters) { body }. They're especially useful for short pieces of logic you only need once, like a custom comparison passed directly into std::sort.

Example: Basic Lambda Syntax

cpp
#include <iostream>

int main() {
	auto sayHello = []() { std::cout << "Hello from a lambda!" << std::endl; };
	sayHello();
	return 0;
}

Lambda with Parameters

Lambdas accept parameters exactly the way regular functions do, written inside the parentheses — [](int a, int b) { return a + b; } takes two ints and returns their sum, just as a named function with the same signature would.

Example: Lambda with Parameters

cpp
#include <iostream>

int main() {
	auto add = [](int a, int b) { return a + b; };
	std::cout << add(3, 4) << std::endl;
	return 0;
}

Lambda Return Types

A lambda's return type is usually inferred automatically from its body, but you can specify it explicitly with a trailing arrow, like [](int x) -> double { return x / 2.0; }, which is occasionally necessary when the compiler can't unambiguously infer the intended type on its own.

Example: Lambda Return Types

cpp
#include <iostream>

int main() {
	auto divide = [](int a, int b) -> double { return (double)a / b; };
	std::cout << divide(7, 2) << std::endl;
	return 0;
}

Lambda Capture Clause

The capture clause [] controls which variables from the surrounding scope the lambda can access inside its body: [=] captures everything by value (a copy), while [&] captures everything by reference (direct access to the originals), and you can also list specific variable names to capture just those.

Example: Lambda Capture Clause

cpp
#include <iostream>

int main() {
	int factor = 10;
	auto multiply = [=](int x) { return x * factor; };
	std::cout << multiply(5) << std::endl;
	return 0;
}

Generic Lambdas

Since C++14, marking a lambda's parameters with auto instead of a specific type — [](auto x, auto y) { return x + y; } — creates a generic lambda that can accept different argument types at different call sites, similar in spirit to a template function but written inline.

Example: Generic Lambdas

cpp
#include <iostream>

int main() {
	auto add = [](auto x, auto y) { return x + y; };
	std::cout << add(2, 3) << std::endl;
	std::cout << add(2.5, 3.5) << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.