2

I'm trying to experiments with inline function. I think that the substitution of function's body executed at preprocessing time. But it is not true. If we declare inline function as the follwoing

//--main.cpp--//
....
inline void bar();
....

and running g++ -E main.cpp then we can to see inline function without changes. So when does substitution body function executed?

  • 2
    Why do you think that? That's not at all what `inline` is for. Don't guess. Verify. – Kerrek SB May 12 '14 at 09:47
  • You probably read somewhere that an inline function is somewhat similar to a function defined as a macro. While this is true in a limited sense, macro substitution happens during preprocessing, whereas inlining takes place much later during compilation. – Paul R May 12 '14 at 09:50
  • `inline` has nothing to do with either function inlining or the preprocessor. See [this](http://stackoverflow.com/a/1759575/485561) question and answer. – Mankarse May 12 '14 at 09:54
  • @Dmitrii Its probably a terrible idea to do it unless you really know that you should, but most compilers support a way of forcing a function to be inlined as well. – RamblingMad May 12 '14 at 10:13

1 Answers1

4

Funcion inlining is a compile time action. Note, inline is not a command, it is a request to compiler, and compiler is free to ignore it. For example, large methods, recursive methods, methods containing loops or other method invocation are usually not inlined. When compiler do performs inlining, it replaces method call with method body, somewhat similar to macro expansion, but this process is more complex. Compiler does not blindly replace method invocation unlike macro, it must take care of parameters to the method.

According to the standard

A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The 
inline specifier indicates to the implementation that inline substitution of the function body at the  
point of call is to be preferred to the usual function call mechanism. An implementation is not required  
to perform this inline substitution at the point of call; 
Rakib
  • 7,435
  • 7
  • 29
  • 45
  • Thanks for your answer. But there is no anything about it in the stadard. Why do you think so? –  May 12 '14 at 09:54