1) The answer is recursion of course. This means that function
string mysteryRecursive(int counter)
calls itself. Of course there should be a way to stop the recursion (as in other case there would be an infinite recursion loop).
That condition is fulfilled by the argument of the function:
counter
. See in line 17 that counter is first decreased then used as argument (because of the prefix decrement operator
--counter
.
When enter inf function
mysteryRecursive
the argument is examined to 0 (line 10):
if (counter == 0)
. If this condition is true line 12
return result;
is executed and the function never goes beyond this line.
The first encounter of return terminates the function.
So that is why string is increased. I hope that answers your first question.
2) Now that I hope you got the picture of recursion examine how it is invoked:
-line 20 is executed first
cout << mysteryRecursive(5);
where
mysteryRecursive()
is invoked with argument 5.
-Inside this function now (that is recursive) a recursive loop starts. Since argument is different than 0 the execution continues up to line 17 where a new invocation of the function is found:
result = "*" + mysteryRecursive(--counter);
Consider that up to now we haven't reached line 18
cout << "Result is " << result << endl;
but we have reached line 16
cout << "Counter is " << counter << endl;
. This will continue until condition in line 10 is fulfilled. Then it will return the string created.
That's why all
appear before all
.
Hope that solved some questions. Be cautious though recursion is powerful but rather subtle point of the language.