我无法理解函数的递归。怎么运行的?这些值是如何存储和所有? [英] I am not able to understand the recursion of functions. How it works? how the values are stored and all?

查看:250
本文介绍了我无法理解函数的递归。怎么运行的?这些值是如何存储和所有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能够理解函数的递归。怎么运行的?这些值是如何存储和所有?

  INT tree_size(结构节点*节点){
  如果(节点== NULL){
    返回(0);
  }其他{
    回报(tree_size(与于节点GT;左)+ tree_size(与于节点的GT;右)+ 1);
  }
}


解决方案

当进入一个函数,一个新的堆栈帧创建(在内存堆栈)。栈帧跟踪该函数内的局部数据,如本地定义的变量和参数传入的。 (和其他的东西,如返回地址和previously存储寄存器的值必须是preserved,但是这是不是这个问题的相关性。)

使用递归,当您从同一个函数中调用一个函数,创建一个新的堆栈帧(与任何电话),以及新的堆栈帧将存储在本地变量的新呼叫。

由于C.斯托尔指出的那样,在两个电话的顺序是不确定的,由于+运算符。

I am not able to understand the recursion of functions. How it works? how the values are stored and all?

int tree_size(struct node* node) { 
  if (node==NULL) {
    return(0); 
  } else { 
    return(tree_size(node->left) + tree_size(node->right) + 1); 
  } 
}

解决方案

When entering a function, a new stack frame is created (on the stack in memory). The stack frame keeps track of the local data within that function, such as locally defined variables and incoming arguments. (And other things such as return address and previously stored register values that must be preserved. However this is not as relevant for this question.)

With recursion, when you call a function from within the same function , you create a new stack frame (as with any call), and that new stack frame will store the local variables for the new call.

As C. Stoll pointed out, the order of the two calls is unspecified, due to the + operator.

这篇关于我无法理解函数的递归。怎么运行的?这些值是如何存储和所有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆