Does tail recursion support shorten the stack for other function calls?

Can languages ​​that support tail recursion apply the same method to non-recursive function calls?

For example, if the last thing the foo function does is return the value of the bar call, can the language drop the stack stack foo ? Are any languages ​​really known?

+3
source share
2 answers

Yes maybe. For example, consider the following C code:

 int f(); int g() { return f(); } 

When I compile this with gcc 4.6.3 with -O3 on x86-64 , I get the following assembly for g() :

 g: xorl %eax, %eax jmp f ; <==== unconditional jump to f 
+1
source

Erlang does :

Tail recursion, as can be seen here, does not increase memory, because when a virtual machine sees a function that calls itself in the tail position (the last expression to be evaluated in the function), it removes the current frame stack. This is called Tail Call Optimization (TCO) and it is a special case of a more general optimization called Last Call Optimization (LCO).

LCO is executed whenever the last expression needs to be evaluated in the Body function - this is another function call. When this happens, as with TCO, Erlang VM avoids storing the stack frame. Since such tail recursion is also possible between several functions. As an example, the chain of the function a () → b (). b () → c (). c () → a (). will effectively create an infinite loop that will not disappear from memory, since the LCO avoids stack overflows. This principle, combined with our use of batteries, makes tail recursion useful.

+2
source

Source: https://habr.com/ru/post/1501112/


All Articles