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?
Unfortunately, the C# compiler doesn't support tail recursion, which is a pity, since the CLR supports it.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With