在gcc /克++尾递归(Tail recursion in gcc/g++)

2019-08-20 19:57发布

我试图寻找,但未能找到:什么是功能的必要条件,这样GCC将优化尾递归? 是否有可能包含有最重要的情况下,任何参考或列表? 由于这是特定版本的,我的兴趣是4.6.3或更高版本(在新越好)。 然而,事实上,任何具体的参考,将不胜感激。

提前致谢!

Answer 1:

With -O2 enabled, gcc will perform tail call optimization, if possible. Now, the question is: When is it possible?

It is possible to eliminate a single recursive call whenever the recursive call happens either immediately before or inside the (single) return statement, so there are no observable side effects afterwards other than possibly returning a different value. This includes returning expressions involving the ternary operator.
Note that even if there are several recursive calls in the return expression (such as in the well-known fibonacci example: return (n==1) ? 1 : fib(n-1)+fib(n-2);), tail call recursion is still applied, but only ever to the last recursive call.

As an obvious special case, if the compiler can prove that the recursive function (and its arguments) qualifies as constant expression, it can (up to a configurable maximum recursion depth, by default 500) eliminate not only the tail call, but the entire execution of the function. This is something GCC does routinely and quite reliably at -O2, which even includes calls to certain library functions such as strlen on literals.



文章来源: Tail recursion in gcc/g++