Поскольку вызов функции рекурсии хранится в стеке. Таким образом, когда один вызов функции возвращается, он выплывает из стека, а затем он выполняет следующую строку вызова функции.
void countdown(int n){
cout << n << endl; // This line calls 4 3 2 1 0
if (n > 0){
countdown(n-1); // function calls itself
}
cout << n << endl;; //This line print 0 1 2 3 4
}
Пусть числа до строки кода являются номера строк:
1 void countdown(int n){
2 cout << n << endl; // This line calls 4 3 2 1 0
3 if (n > 0){
4 countdown(n-1); // function calls itself
5 }
6 cout << n << endl;; //This line print 0 1 2 3 4
7 }
Suppose countdown is called with n = 2,
Then, Your stack will initially contain function call with n = 2.
Because of line 2, 2 gets printed.
Because of line 4, function with n = 1 gets called. So, now stack has 1|2
Now because of line 2 again, 1 gets printed.
Because of line 4, function with n = 0 gets called. So Now stack is 0|1|2
Line 2 prints 0.
Line 3 condition fails and so line 4 is not executed.
Line 6 prints 0.
Line 7 tells that function execution is over and hence it will pop out of stack. Now stack is 1|2.
Now, function with n = 1 resumes its operation from line 5.
So, line 6 makes it print 1.
line 7 tells that function execution is over and hence it will pop out of stack. Now stack is 2.
So, function with n =2 resumes its operation from line 5.
line 6 makes it print 2.
line 7 tells function execution is over and hence it will pop out of stack. And now it will return to main.
Подсчет в обратном направлении происходит от второго соиЬ вызова. –