且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++ 函数的递归

更新时间:2022-06-27 01:05:35

您熟悉堆栈吗?

函数调用自身,向上打印每个数字,然后从最后的递归调用返回,向下遍历数字,因为它重复从递归返回.它只执行递归之后包含的其余代码打电话.

The function calls itself,and prints every number upwards,then it returns from the final recursive call,going downwards through the numbers,as it return from recursion repeatedly.It just executes the rest of the code that it contains after the recursive call.

一个简单的表示是:

    print_numm(1):
    cout << 1
    print_numm(1+1):
        cout << 2
        print_numm(2+1):
            cout << 3
            print_numm(3+1):
                cout << 4
                print_numm(4+1):
                    cout << 5
//now the number is bigger than 4 so the function
//will return from recursion
                    cout << 5
//now the function is done,but the function that called print_numm(5) is waiting to finish
//so it executes the rest of the code printing 4,same with all waiting for print_numm(4) and so on
                cout << 4
            cout << 3
        cout << 2
    cout << 1