Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About Tail recursive optimization

I used the below two functions to test the Tail recursive optimization under MSVC08

int TailRecursively1(int i)
{
  return TailRecursively1(i);
}

int TailRecursively2(std::string str)
{
  return TailRecursively2(str);
}

why has TailRecursively1 been optimized, but TailRecursively2 has caused the stack overflow?

like image 203
Squall Leonhart Avatar asked Jan 12 '13 16:01

Squall Leonhart


People also ask

How does tail call optimization work?

Tail call optimization happens when the compiler transforms a call immediately followed by a ret into a single jmp . This transformation saves one instruction, and more importantly it eliminates the implicit push/pop from the stack done by call and ret .

Why is tail recursion used?

In tail recursion, there is no other operation to perform after executing the recursive function itself; the function can directly return the result of the recursive call. In simple words, in tail recursion, the recursive function is called last. So it is more efficient than non-tail recursion.

What is recursive optimization?

There are many problems where you are trying to do optimization. That is, you are attempting to find a way of doing something that maximizes or minimizes some quantity. A recursive divide and conquer approach is often successful for dealing with such problems.

Which languages optimize tail recursion?

Tail Recursion Elimination is a very interesting feature available in Functional Programming languages, like Haskell and Scala. It makes recursive function calls almost as fast as looping.


1 Answers

Because there are calls for std::string copy constructor and destructor when sending the str parameter by value to TailReucrsively2?

(I'm not 100% sure about this)

like image 164
tohava Avatar answered Sep 21 '22 13:09

tohava