Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tail recursion optimization happens in visual studio 10 x64 debug but not in release?

originally I got a stackoverflow exception in x86 mode. As I noticed that x64 would optimize tail recursion so i switched to compile in x64. And it worked out gracefully in debug mode.. However when I tried to run the release code.. it throwed stackoverflow again.. any possible reason?

like image 396
colinfang Avatar asked Sep 02 '11 09:09

colinfang


People also ask

Is C# optimized for tail recursion?

Unfortunately, the C# compiler doesn't support tail recursion, which is a pity, since the CLR supports it.

Is tail recursion always possible?

Not every recursive function can be turned into a tail-recursive function. In particular, if a function makes a recursive call, but then examines the result and does different things depending on its value, then it may not be possible to make the function tail-recursive.

How does compiler optimize tail recursion?

The idea used by compilers to optimize tail-recursive functions is simple, since the recursive call is the last statement, there is nothing left to do in the current function, so saving the current function's stack frame is of no use (See this for more details).

Does C# support tail call optimization?

C# does not support TCO, however, the VM it runs within, Common Language Runtime (CLR) supports TCO. Functional languages such as Haskell, F#, Scala and Elixir support TCO.


1 Answers

The rules for when tail recursion optimizations are applied are complicated and ever-changing.

I would strongly recommend that you don't rely on tail recursion from a correctness point of view.

like image 69
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet