How exactly does tail recursion work?

前端 未结 8 1585
粉色の甜心
粉色の甜心 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;
    }
    
    0 讨论(0)
  • 2020-12-07 08:01

    My answer is more of a guess, because recursion is something relating to internal implementation.

    In tail recursion, the recursive function is called at the end of the same function. Probably compiler can optimize in below way:

    1. Let the ongoing function wind up (i.e. used stack is recalled)
    2. Store the variables which are going to be used as arguments to the function in a temporary storage
    3. After this, call the function again with the temporarily stored argument

    As you can see, we are winding up the original function before the next iteration of the same function, so we are not actually "using" the stack.

    But I believe if there are destructors to be called inside the function then this optimization may not apply.

    0 讨论(0)
提交回复
热议问题