9.5 FUNCTION INLINING IN C


9.5 FUNCTION INLINING IN C++

Function inlining—an important part of the code optimization that can be carried out by modern compilers—involves replacing a function call with the body of the function in order to eliminate the overhead associated with the function call, with parameter passing, and with the passing of the return object. If so directed through appropriate command line options, a compiler will scan the source code for candidate functions suitable for inlining. These are usually small and frequently used functions with not too much branching.

In C++, all member functions that are defined within a class—as opposed to just being declared there through their prototypes—are by default assumed to be inline functions. And all member functions that are only declared inside a class definition but defined outside are by default assumed to be non-inline functions. However, if a programmer wishes for a member function that is defined outside a class to be considered as a candidate for inlining, the function must be explicitly declared to be inline.

In the following example, the function foo() is by default considered to be an inline function because it is defined inside the class definition.

 class x {      //      void foo() {          // body of function      }      void bar(); }; 

On the other hand, the function bar() is only declared inside the class definition. If we wanted this function to also be a candidate for inlining, its outside definition would have to include the keyword inline:

       inline void X::bar() {           // body of function       } 

Member function declared inline must be included in the same file as the class definition for the inlining declaration to be effective.

Stand-alone functions can also be declared to be inline in the same manner. But note that the inline declaration, whether for class member functions or stand-alone functions, is only a recommendation to the compiler. Depending on its competence level, a compiler has the option of ignoring the recommendation, or implementing it only partially. To see how an inlining recommendation may be honored only partially, consider the case where a function f1 calls a function f2, which in turn calls a function f3, all functions declared inline. A compiler may choose to only carry out inlining up to level 1, meaning that inside f1 it will replace a call to f2 by the body of f2, but inside f2 it will leave the function call to f3 unchanged.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net