c++ - 这个函数真的是尾递归的吗?

标签 c++ c tail-recursion

我在 Programming Interviews Exposed(第 3 版)中读到了递归,其中介绍了以下递归 factorial 函数:

int factorial(int n){
    if (n > 1) { /* Recursive case */
        return factorial(n-1) * n;
    } else {     /* Base case */
        return 1;
    }
}

在同一页的底部(第 108 页),他们讨论了尾递归函数:

Note that when the value returned by the recursive call is itself immediately returned, as in the preceding definition for factorial, the function is tail-recursive.

但这里真的是这样吗?函数中的最后一个调用是 * 调用,那么这个栈帧是否会被保留(如果我们不考虑编译器优化)?这真的是尾递归吗?

最佳答案

您可以将其重写为尾递归:

int factorial(int n){
    return factorial2(n, 1);
}
int factorial2(int n, int accum) {
    if (n < 1) {
       return accum;
    } else {
        return factorial2(n - 1, accum * n);
    }
}

关于c++ - 这个函数真的是尾递归的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115657/

相关文章:

c++ - 字符串比较 C++ 中的奇怪行为

c - Netcat套接字编程

mysql - 在c中调用MySQL存储过程,传递变量参数

c# - 额外的 ldnull 和 tail 的目的是什么。在 F# 实现与 C# 中?

recursion - OCaml 二叉树深度,无堆栈溢出

c++ - GLSL 统一缓冲 block 为空

c++ - 将函数定义为速记

c++ - 在 Arduino 上使用 sscanf() 将最后一个字节归零

c - 通过初始化程序设置结构数组元素的语法?

c - 尾递归 [C]