C++

Lambda Expressions

12 question(s)

What is an immediately invoked lambda expression (IILE) and why use it?

Intermediate
An IILE is a lambda that is called right where it's defined, using a trailing (). It's used to initialize a const variable with complex logic, to scope temporary variables, or to run one-off initialization while keeping the result const and the setup contained.
const int config = []{
    int v = load();
    return v * 2;
}();  // invoked immediately
Real-world example An IILE computes a complex const configuration value inline while keeping helper variables local.

Common follow-ups: How does an IILE help with const? | What are the parentheses at the end for?

Lambda Expressions Const Correctness Lambda Expressions

Can a lambda be recursive?

Beginner
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?

Lambda Expressions Modern C++ Lambda Expressions