How exactly does tail recursion work?

前端 未结 8 1612
粉色の甜心
粉色の甜心 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

    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.

提交回复
热议问题