Can lambda functions be recursive? [duplicate]

Yes, they can. Starting with C++23 you can use the explicit this parameter:

auto factorial = [](this auto self, int i) 
{ 
    return (i == 1) ? 1 : i * self(i - 1); 
};

With previous C++ standards, you can store the lambda in a variable and reference that variable (although you cannot declare the type of that variable as auto, you would have to use an std::function object instead). For instance:

std::function<int (int)> factorial = [&] (int i) 
{ 
    return (i == 1) ? 1 : i * factorial(i - 1); 
};

Leave a Comment