How exactly does tail recursion work?

前端 未结 8 1591
粉色の甜心
粉色の甜心 2020-12-07 07:39

I almost understand how tail recursion works and the difference between it and a normal recursion. I only don\'t understand why it doesn\'t

8条回答
  •  感情败类
    2020-12-07 08:01

    Tail recursion can usually be transformed into a loop by the compiler, especially when accumulators are used.

    // tail recursion
    int fac_times (int n, int acc = 1) {
        if (n == 0) return acc;
        else return fac_times(n - 1, acc * n);
    }
    

    would compile to something like

    // accumulator
    int fac_times (int n) {
        int acc = 1;
        while (n > 0) {
            acc *= n;
            n -= 1;
        }
        return acc;
    }
    

提交回复
热议问题