How exactly does tail recursion work?

前端 未结 8 1611
粉色の甜心
粉色の甜心 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 07:45

    Compiler is enough intelligent to understand tail recursion.In case, while returning back from a recursive call,there is no pending operation and recursive call is the last statement, fall under the category of tail recursion. Compiler basically performs tail recursion optimization, removing stack implementation.Consider below code.

    void tail(int i) {
        if(i<=0) return;
        else {
         system.out.print(i+"");
         tail(i-1);
        }
       }
    

    After performing optimization , the above code is converted into below one.

    void tail(int i) {
        blockToJump:{
        if(i<=0) return;
        else {
         system.out.print(i+"");
         i=i-1;
         continue blockToJump;  //jump to the bolckToJump
        }
        }
       }
    

    This is how compiler does Tail Recursion Optimization.

提交回复
热议问题