I was trying to use lambda function recursively as below.
#include <iostream>
#include <functional>
using namespace std;
int main()
{
std::function<int(int)> x = [](int y) -> int {
if(y == 0) {
return 0;
} else {
return y + x(--y);
}
};
cout << x(3) << endl;
}
But it is throwing below errors.
main.cpp: In lambda function:
main.cpp:20:24: error: ‘x’ is not captured
return y + x(--y);
^
main.cpp:16:34: note: the lambda has no capture-default
std::function<int(int)> x = [](int y) -> int {
^
main.cpp:16:29: note: ‘std::function x’ declared here
std::function<int(int)> x = [](int y) -> int {
^
Is this throwing error because x is not fully defined when compiler reaches x(--y)? Can any one please let me know how to fix this issue.