简体   繁体   中英

Tail recursion optimization in C++ code

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?

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM