How exactly does tail recursion work?

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

    Here is a simple example that shows how recursive functions work:

    long f (long n)
    {
    
        if (n == 0) // have we reached the bottom of the ocean ?
            return 0;
    
        // code executed in the descendence
    
        return f(n-1) + 1; // recurrence
    
        // code executed in the ascendence
    
    }
    

    Tail recursion is a simple recursive function, where recurrence is done at the end of the function, thus no code is done in ascendence, which helps most compilers of high-level programming languages to do what is known as Tail Recursion Optimization, also has a more complex optimization known as the Tail recursion modulo

提交回复
热议问题