加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C上的递归向后返回

发布时间:2020-12-16 10:13:11 所属栏目:百科 来源:网络整理
导读:这是代码: #include iostreamusing namespace std;void countdown(int n);int main(){ countdown(4); // call the recursive function return 0;}void countdown(int n){ cout n endl; if (n 0){ countdown(n-1); // function calls itself } cout n endl;
这是代码:

#include <iostream>
using namespace std;
void countdown(int n);

int main(){
    countdown(4); // call the recursive function
    return 0;
}

void countdown(int n){
    cout << n << endl;

    if (n > 0){
        countdown(n-1); // function calls itself
    }

    cout << n << endl; // intended part of code
}

简单运行:

4
3
2
1
0
0
1
2
3
4

问题:为什么这个递归函数从0重新计数到4并且不在0处停止?

解决方法

因为递归函数调用存储在堆栈中.因此,当一个函数调用返回时,它会从堆栈中弹出,然后执行函数调用的下一行.

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读