Advertisement
Beginner C++, Lambda Expressions

What is a lambda expression in C++?

Short answer

A lambda expression is an anonymous function object defined inline, introduced in C++11. It has the form [captures](params){ body } and can be stored, passed to algorithms, or called immediately. The compiler generates a unique closure type with an operator() containing the body.

Save C++ mock interview
Advertisement
AModel answer
A lambda expression is an anonymous function object defined inline, introduced in C++11. It has the form [captures](params){ body } and can be stored, passed to algorithms, or called immediately. The compiler generates a unique closure type with an operator() containing the body.
auto add = [](int a, int b) { return a + b; };
int r = add(2, 3);  // 5
Real-world example
A lambda is passed to std::sort to define a custom comparison inline instead of a named function.
Likely follow-ups
  • What is the closure type? | Where are lambdas commonly used?
Related topics