Possible Duplicate:
Can a recursive function be inline?
I think that recursive function defined as inline will not have any effect and won't be made inline at all. Because, the compiler doesn't know how many levels to replicate the code of inline function. Any thoughts?
I tried browsing related SO questions to find a clear existing answer for you, but alas…
So, the keywoard inline
(or a member function being implicitly inline by defined in the class definition) has two effects:
It guarantees that the function can be defined in multiple translation units without violating the One Definition Rule, i.e. in practice, without the linker protesting about multiple definitions. For this use all definitions of the functions must be inline
, and they must be identical.
It serves as a vague hint to the compiler to inline the machine code for calls to the function. Some calls may be inlined, some not. The degree of inlining may vary, and a compiler may even completely ignore this hint (in practice, g++ has a tendency to follow the hint to absurd and perhaps ungood degree, while Visual C++ more like ignores it).
For a recursive function, if a compiler follows the hint for any particular call of the function, then the call may be expanded to one or two or three or whatever levels of recursion. It's a difficult thing to do, so don’t count on it. Also, the compiler’s own heuristics for inlining are probably better than your gut feeling, because the compiler has a more global view of things (it knows more), so, summing up:
Don't use inline
for the hinting effect, use it for the ODR guarantee.
Where you’re absolutely sure that you do know better than the compiler, and where you have abided by principles such as "measure first" and "don't do premature optimization", you may be able to get more reliable control of inlining via compiler specific language extensions or pragmas.
Cheers & hth.,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With