Sofia190
Sofia190

Reputation: 53

Recursive calls when the condition is doubled

Here is the question: This program repeats the if condition twice; how will the recursive calls work inside each if block is what seems a little bit not that simple.

I am trying to understand if the execution from the first recursive call will jump to the second if block or if for every value of c, there will be another two recursive calls because the function has two recursive calls; here the value of the variable c meaning after it is processed inside the function with the subtraction operation.

Thanks to all!

#include <iostream>

using namespace std;

void ex(char c);

void ex(char c) { 
   if (c >'a') { 
       ex(c-1);
   }  

   cout<< c;    

   if (c>'a') { 
     ex(c-1);
   } 
}

int main()
{
   ex('c');
}

Upvotes: 0

Views: 62

Answers (1)

bruno
bruno

Reputation: 32596

A recursive call like a non recursive call, the called function starts from its beginning.

If the compiler detect the recursive call is terminal the new call is not added in the stack but replaced by the equivalent of a jump (but still going at the beginning except few instructions about the stack management). Your second recursive call is terminal.

You can see the calls using a debugger or modifying your code to have :

#include <iostream>

using namespace std;

void ex(char c, string indent = string()) { 
   cout << indent << "enter with " << c << endl;

   if (c >'a') { 
       ex(c-1, indent + "@");
   }  

   cout<< indent << c << endl;    

   if (c>'a') { 
     ex(c-1, indent + "$");
   } 

   cout << indent << "exit with " << c << endl;
}

int main()
{
   ex('c');
}

Compilation and execution :

pi@raspberrypi:/tmp $ g++ a.cc
pi@raspberrypi:/tmp $ ./a.out
enter with c
@enter with b
@@enter with a
@@a
@@exit with a
@b
@$enter with a
@$a
@$exit with a
@exit with b
c
$enter with b
$@enter with a
$@a
$@exit with a
$b
$$enter with a
$$a
$$exit with a
$exit with b
exit with c
pi@raspberrypi:/tmp $ 

The deep of the indent is the deep of the recursive call, and @/$ indicates where the calls was

Upvotes: 2

Related Questions