7

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?

Community
  • 1
  • 1
Boolean
  • 14,266
  • 30
  • 88
  • 129

3 Answers3

3

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.,

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
2

Obviously it won't be able to repeat the code ad infinitum. There might be a way to do it in a limited fashion, ala loop unrolling, but that would probably be more difficult for the compiler to determine than a simple for(int i=0; i < 5; ++i) loop.

Also available to the compiler is a tail call if the function is coded in a special way. While it doesn't repeat the assembly byte by byte at the point of the call, it can avoid setting up a stack frame and calling the function and replace it with just a jmp instruction, making the function call require no less overhead than an if statement.

user470379
  • 4,879
  • 16
  • 21
0

This is already addressed here Can a recursive function be inline?

Community
  • 1
  • 1
Neera
  • 1,577
  • 8
  • 10