C++ Snippet

C++ Lambda Basics

Difficulty: Easy

Lambdas (C++11+) are first-class anonymous function objects with a compact syntax: `[capture](params) { body }`. This snippet covers the basic form, the difference between by-value `[=]` and by-reference `[&]` captures, and using lambdas with standard algorithms like `std::sort` and `std::for_each`. Reach for them anywhere you would write a small functor or pass a callback.

Code Snippets
/

C++ Lambda Basics

C++ Lambda Basics

Lambdas (C++11+) are first-class anonymous function objects with a compact syntax: `[capture](params) { body }`. This snippet covers the basic form, the difference between by-value `[=]` and by-reference `[&]` captures, and using lambdas with standard algorithms like `std::sort` and `std::for_each`. Reach for them anywhere you would write a small functor or pass a callback.

C++
Easy
3 snippets
cpp-lambdas
functional-programming
cpp-stl

212 views

3

The square brackets are the capture clause; the parentheses are the parameter list; the braces are the body. The compiler synthesises a closure type with operator(), so the lambda is callable like any function object. auto add = [](int, int) { ... }; stores it in a variable; passing it inline to algorithms is more common. The return type is deduced; you can specify it explicitly with -> int after the parameter list when deduction would be ambiguous.