Recursive Function Inlining
It's a common misconception that recursive functions cannot be inlined. However, compilers can indeed inline recursive functions, albeit with certain considerations.
Inline Qualifier vs. Compiler Optimization
The inline specifier on a function is merely a hint to the compiler. The compiler has the final say whether to inline the function or not, regardless of the inline qualifier.
Compiler's Inlining Decision
A compiler decides whether to inline a function based on factors such as:
Example Inlining Optimization
Consider the following recursive factorial function:
<code class="cpp">inline int factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); }</code>
An optimizing compiler could potentially inline this function to a certain level, as seen in the following optimized code:
<code class="cpp">int factorial(int n) { if (n <= 1) return 1; else { int n2 = n - 1; if (n2 <= 1) return n * 1; else { int n3 = n2 - 1; if (n3 <= 1) return n * n2 * 1; else return n * n2 * n3 * factorial(n3 - 1); } } }</code>
In this case, the compiler has unrolled the factorial function three times, effectively inlining a portion of the recursive calls.
The above is the detailed content of Can Recursive Functions Be Inlined?. For more information, please follow other related articles on the PHP Chinese website!