kadina
kadina

Reputation: 5376

Recursive std::function is throwing errors

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.

Upvotes: 0

Views: 70

Answers (1)

selbie
selbie

Reputation: 104514

Updated

This line looks suspcious:

return y + x(--y);

You're decrementing y and evaluating it within the same expression. The rules vary between "defined" and "undefined" on statements like this. But I suspect you really want this:

return y + x(y-1);

Split your declaration of x separate from the assignment. And capture x by reference:

int main()
{
    std::function<int(int)> x;
    x = [&x](int y) -> int {
        if (y == 0) {
            return 0;
        }
        else {
            return y + x(y-1);
        }
    };

    cout << x(3) << endl;
}

The result is that 6 will get printed.

Upvotes: 3

Related Questions