lundi 24 juillet 2023

How to solve "Use of auto func(int) before deduction of auto" in C++ [duplicate]

I was trying to use recursion function to calculate factorial of a number. But this time I tried to use the lambda function as a recursive function. The code is below-

#include<iostream>
using namespace std;
auto factorial = [](int n)->int
{
    if(n==0 || n==1)
        return 1;
    else
        return n*factorial(n-1);
};
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    cin>>n;
    cout<<factorial(n)<<"\n";
    return 0;
}

But the code gives an error which is-

error: use of 'factorial' before deduction of 'auto'

I am not sure what is the meaning of this error and how to solve it. Is it even possible to use lambda function as a recursive function?

I went through these questions here-

But I couldn't figure out how to solve this problem. Can anyone please help with this problem?

Aucun commentaire:

Enregistrer un commentaire