PDA

View Full Version : Can somebody explain me why the compiler has this result in a recursion code in C++?


pandol
11-18-2007, 07:15 PM
Below there is a simple recursion program. My question is why when I Run the program I get "11" times the expression "Hello World" instead of "1"?
I would expect to get:
"My name"
"Hey"
"Hello world"

#include <iostream>

using namespace std;

void doll ( int size )
{
if ( size == 0 ) // No doll can be smaller than 1 atom (10^0==1) so doesn't call itself
{
printf("My name\n");
printf("Hey\n");
}
else
{
doll ( size - 1 ); // Decrements the size variable so the next doll will be smaller.
}
printf("Hello world\n");
}


int main()
{
doll ( 1 ); //Starts off with a large doll (its a logarithmic scale)
}

rpgfan3233
11-18-2007, 11:38 PM
***ENTER 'doll' call (size=1)***
size == 0? No.
***ENTER 'else' block***
***ENTER 'doll' nested call (size=0)***
size == 0? Yes.
***ENTER 'if' block***
Output "My name\n"
Output "Hey\n"
***EXIT 'if' block***
Output "Hello World\n"
***EXIT 'doll' nested call (size=0)***
***EXIT 'else' block***
Output "Hello World\n"
***EXIT 'doll' call (size=1)***That's pretty much it. The final output would be:

My name
Hey
Hello World
Hello World

By the way, any reason for not using std::cout? If you only need printf, #include <cstdio> instead of #include <iostream>.

Gox
11-19-2007, 10:14 AM
rpgfan gave you a good explanation, as well as what the output for your code is.
I don't know how you got Hello World 11 times, because the code you provided doesn't do that. The exact output from your code is
My name
Hey
Hello World
Hello World

See rpgfan's explanation as to why this is so.