This program recursively calls the function tester.
#include <iostream>
void tester();
int i = 1;
int k = 1;
int main() {
tester();
}
void tester() {
while(i++ < 10)
tester();
std::cout << "called " << k++ << " times" << std::endl;
}
I am surprised by this output :
called 1 times
called 2 times
called 3 times
called 4 times
called 5 times
called 6 times
called 7 times
called 8 times
called 9 times
called 10 times
and it is because this is the way i understand this program :
After the first call to tester from main it enters a loop. The first statement of the loop calls the function tester again, and this carries on.After looping 10 times the statement following the while loop should work i.e only once . So the output should be :called 1 times . But this isn’t actually happening ! Why ? How does this program work ?
The
whilebody is executed only once in each recursive depth. Thewhileis false wheniis10, which will be whentester ()is called 10 times recursively. As theiis declared global, thei++update will be visible to each call oftester ().At the last recursive depth when the
whilecondition is false, the lasttester ()call will return to its previous depth. At this moment, the next iteration of thewhileloop will be false asiis10. Thecoutstatement will be encountered after eachwhileloop is terminated, which will sequentially print the values ofk, incrementing at each recursive depth, as the recursion rolls back.Manually trace what happens to understand the stuff.
UPDATE
Have a look at the execution output. Especially note the
dparameter, which denotes the recursive depth. At each depth thewhileloop has iterated one time, upto the last “while is true, tester called” output. At depth 10, thewhileis false as it is 10, and first time it returns back the control to its previous depth level, (the first “return back” wheniis10). After it returns the control returns to the body of thewhileloop of the last level, from which the function was called (from which it just returned), and the next iteration of this loop will be false, (i is global and 10 or more), therefore this also returns. Similarly, at each recursive depth the 2nd iteration ofwhileloop is false, and it keeps returning. Check out the output.And here is the test code. I hope the description is much clear now (?). Analyzing this will help.