C++ › Lambda Expressions

Can a lambda be recursive?

Beginner

Answer

A lambda can't directly refer to itself by name because it's anonymous and, with auto, its type isn't known during initialization. Workarounds include storing it in a std::function (which can be captured by reference), or in C++23 using the 'deducing this' feature to allow self-reference. Often a named function is simpler for recursion.
std::function<int(int)> fac =
    [&](int n){ return n <= 1 ? 1 : n * fac(n-1); };
Real-world example A recursive lambda held in std::function computes a factorial within a local scope.

Common follow-ups: Why can't auto lambdas self-refer directly? | What does C++23 add for this?