Home > other >  Multiple Recursion Calls
Multiple Recursion Calls

Time:08-07

#include <iostream>

using namespace std;
int y(int i){
    cout<<i<<endl;
    i  ;

    if(i==10){
        return 10000000;
    }
    int left=y(i);
    int right=y(i) 1;
    return right;

}
int main()
{
    cout<<y(1);

    return 0;
}

In this code after left(9) has executed shouldn't "i" come out of the stack and execute right(1) ?But while debugging I have noticed that right(9) gets executed.Could someone please explain this to me.Thank you in advance.

CodePudding user response:

Exection doesn't come out of the stack. Each return removes one call.

so when i==9 the call in int left=y(9) will be followed by the call in int right=y(9) 1 because i==9 still.

Only then will the call to y(8) return and so on through y(7),y(6) and so on down to the original call in main() of y(1).

Like any stack structure it is unloaded in the reverse order it's built.

Personally I think of those clever plate dispensers where the weight of the plates is balanced by a spring.

When you call a function you create a new local environment (put a new plate on the stack) and a function returns the top plate is discarded.

When you discard the bottom plate you're returning from main() and the program finishes.

Imagine y(9) printed on the top plate and y(8) on the one underneath. At the end is a instrumented version of the code showing the stack size and number of calls made.

Spring balanced plate stacker frame

#include <iostream>

int y(int i,char from,int &calls,int &stack){
      calls;
      stack;
    std::cout<<"entering y("<< i<<','<<from<<") "<<calls<<' '<<stack<<'\n';
    i  ;

    if(i==10){
        std::cout<<"returning "<<10000000<<" from y(" << i<<','<<from<<") [1]\n";
        --stack;
        return 10000000;
    }
    int left=y(i,'l',calls,stack);
    int right=y(i,'r',calls,stack) 1;
    std::cout<<"returning "<<right<<" from y(" << i<<','<<from<<") [2]\n";
    --stack;
    return right;

}

int main()
{
  int calls{0};
  int stack{1};//We're in main().
  std::cout<<y(1,'m',calls,stack);

    return 0;
}
  •  Tags:  
  • c
  • Related