Recursion - declaring a variable in the body or using it as a parameter?

What is the difference between this recursive function:

int foo (int n,int sum)  
{
    if (n==0)  
        return sum;
    int temp;
    cin>>temp;
    return foo(n-1,sum+temp);
}

int main()
{
    ...
    ...
    foo(n,0);
    ...
    ...
}

      

and this one:

int foo (int n,int sum, int temp)  
{
    if (n==0)  
        return sum;
    cin>>temp;
    return foo(n-1,sum+temp,temp);
}

int main()
{
    ...
    int temp;
    foo(n,0,temp);
    ...
    ...
}

      

which is more efficient in terms of spatial complexity? do they make any difference at all? can we say that recursive calls make a copy of the parameters, declaring a variable in a function is the same as using it as a parameter?

+3


source to share


1 answer


In terms of memory consumption, the function parameter is identical to a local vartiable. That is, there is no difference between the two in terms of memory consumption, other than what you have injected into a main

completely unnecessary local variable.



However, the second option might be less efficient in those days, since at each level of recursion, you pass the current value temp

to the next level of recursion. This value is not used at all (the one received from main

not even initialized), which means that any CPU attempts spent transferring it are completely lost.

+5


source







All Articles