I wanted to see the impact of tail recursion optimization and want to write simple factorial function in a tail recursion optimized way. Is it possible to do this in the code without compiler supporting it?
2 Answers
The compiler does the optimization. So it is not possible to test it without compiler support.
The only way to do this in code is to replace the recursion by iteration (but then of course you lose the recursion).
2 Comments
Tail recursion optimization turns functions with tail recursion property into iteration, to do it without compiler support, you have to do the recursion -> iteration manually. Note that you may lose readability of your code (recursive functions tend to be shorter and easier to understand) and need a lot of code change (thus turning your brains inside out). If I need to do this, I usually put the original recursive function in a comment above the converted iterative version.
2 Comments
while(1) at the top of the function. Replace each tail-recursive call return myfunc(arg1, arg2 ... arg_n); with one line per function parameter to set the new value (if it differs from the current value), followed by a goto or continue. More changes needed if the function isn't simply tail-recursive, but those same changes are needed if the compiler optimizes only simple tail-recursion.