为什么此功能按升序打印1 2 3 4 5

ibr*_*ala 0 c++ recursion

我尝试搜索答案,但无法获得任何令人信服的答案。有人可以解释一下此c ++代码的打印方式1 2 3 4 5吗?

我明白到何时为止n=1。when时n=1fun(n-1) = fun(1-1) = fun(0)由于n>0不满意而没有执行,因此现在cout << n << endl将执行并n仍然等于,1但是在打印后1应该停止?如何处理之前的通话?它如何打印2 3 4 5

同样,在cout << n << endl上方时,fun(n-1)它在打印时也很有意义5 4 3 2 1

#include <iostream>

using namespace std;

void fun(int n)
{
    if (n > 0) {
        fun(n - 1);
        cout << n << endl;
    }
}

int main()
{
    int x = 5;
    fun(x);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码可以打印,1 2 3 4 5而据我所知应该只打印1

H.S*_*.S. 5

每次调用函数时,fun()请记下变量的值,n您可以轻松地跟踪输出。当递归调用fun()返回时,它之后的语句将被执行(wrt函数fun()cout << n << endl;语句)。它像这样工作:

fun(5)    -->   First call : n is 5
5>0 : true
|   fun(5-1)    --> Recursive call 1 : n is 4
|   4>0 : true
|   |   fun(4-1)    --> Recursive call 2 : n is 3
|   |   3>0 : true
|   |   |   fun(3-1)    --> Recursive call 3 : n is 2
|   |   |   2>0 : true
|   |   |   |   fun(2-1)    --> Recursive call 4 : n is 1
|   |   |   |   1>0 : true
|   |   |   |   |   fun(1-1)    --> Recursive call 5 : n is 0
|   |   |   |   |   0>0 : false  --> Return from call 5
|   |   |   |   |
|   |   |   |   Print n (n is 1) and return from call 4
|   |   |   Print n (n is 2) and return from call 3
|   |   Print n (n is 3) and return from call 2
|   Print n (n is 4) and return from call 1
Print n (n is 5) and return from first call to main()
Run Code Online (Sandbox Code Playgroud)

因此,输出为1 2 3 4 5