Question:
Can a compiler inline a recursive function like the following?
inline int factorial(int n) { if(!n) return 1; else return n*factorial(n-1); }
Answer:
Yes, it's possible for a compiler to inline a recursive function, but it's not always guaranteed. The inline keyword is just a hint to the compiler that it might be beneficial to inline the function. The compiler has the final say as to whether or not it will actually perform inlining.
Compiler's Decision Process:
There are various factors that a compiler considers when deciding whether to inline a function or not:
Compiler Optimization Example:
Consider the following code:
inline int factorial(int n) { if (n <= 1) { return 1; } else { return n * factorial(n - 1); } } int f(int x) { return factorial(x); }
An optimizing compiler might inline the factorial function three times, resulting in the following code:
int factorial(int n) { if (n <= 1) { return 1; } else { return n * factorial(n - 1); } } int f(int x) { if (x <= 1) { return 1; } else { int x2 = x - 1; if (x2 <= 1) { return x * 1; } else { int x3 = x2 - 1; if (x3 <= 1) { return x * x2 * 1; } else { return x * x2 * x3 * factorial(x3 - 1); } } } }
This optimization unfolds the recursion up to three levels. The compiler may perform this optimization for certain recursion depths and optimization settings.
The above is the detailed content of Can a Compiler Inline Recursive Functions?. For more information, please follow other related articles on the PHP Chinese website!