LOGBOOK

HELP

Quiz Entry - updated: 2026.07.06

What is a lambda expression in C++?

A lambda is an anonymous (unnamed) inline function, written [captures](params) -> ret { body }.

The four parts of a lambda radiating from the centre: captures, params, return type, body

* The four parts of a lambda: the capture list grabs outer variables, then parameters, an optional return type, and the body. *

// Lambda that compares two ints (descending order)
auto cmp = [](int x, int y) -> bool {
    return x > y;
};

vector<int> v = {3, 1, 4};
sort(v.begin(), v.end(), cmp);   // v is now {4, 3, 1}

// Or written inline, right where it's used:
sort(v.begin(), v.end(), [](int x, int y) { return x > y; });

Parts:

  • [] — capture list (which outer-scope variables it can use)
  • () — parameters
  • -> ret — return type (optional; usually inferred)
  • {} — function body

Tip: Lambdas shine as the throwaway "callback" you hand to STL algorithms like sort, find_if, or for_each — defining the behaviour right at the call site instead of in a separate named function.

Go deeper:

From Quiz: REVE1 / C++ Programming | Updated: Jul 06, 2026