c - 难以理解递归?

标签 c recursion logic

几天前我遇到了一个问题。 问题如下..

int func(n){
  if(n < 4)
    return func(++n) + func(++n);
  return n;
}

我通过调用 func(0) 编译并运行程序,结果为 35。

但我无法想象堆栈树。

谁能描述一下堆栈。

最佳答案

这个问题涵盖了两个不相关的问题。

编写的代码具有未定义的行为。未指定函数是使用 (n+1) 和 (n+2) 调用,还是使用 (n+1) 或 (n+2) 调用两次,或者完全是其他方式调用。标准的相关部分是:C11 n1570 S6.5/2: [EDIT]

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings. 84)

这很容易通过对代码的小改动来解决,如下所示。

int func(n){
  if(n < 4) {
    return func(n+1) + func(n+2);
  }
  return n;
}

真正的问题是这一切是如何运作的。很明显,每个函数都会调用自己两次,或者根本不调用,并且它只能从最低级别返回 4 或 5。这就是二叉树的结构。写出树并标记每个值,您将得到一个由 4 和 5 组成的字符串。它们加起来为 35。

关于c - 难以理解递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25377313/

相关文章:

java - 递归打印

java - 数组循环程序

c - 在 C 中使用数组显示模式

recursion - 编译器如何理解递归?

c - 两个 unsigned long 表示之间的区别

python - 使用递归计算列表的数量?

Java 文件格式化正确顺序

javascript - 我的 javascript 函数陷入了循环......

将 head 程序转换为 tail C

C 程序因使用随机变量而崩溃