简体   繁体   English

C ++代码中的尾递归优化

[英]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. 如果需要这样做,通常会将原始递归函数放在转换后的迭代版本上方的注释中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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