5.10.  inline Functions

[ fromfile: functions.xml id: inlinefunct ]

To avoid the overhead associated with a function call (i.e., creation of a stack frame containing copies of arguments or addresses of reference parameters and the return address) C++ permits you to declare functions to be inline. Such a declaration is a request to the compiler that it replace each call to the function with the fully expanded code of the function. For example:

inline int max(int a, int b){
  return a > b ? a : b ;
}

int main(){
   int temp = max(3,5);
    etc....
}

The compiler could substitute the expanded code for max as shown here.

int main() {
  int temp;  
  {
    int a = 3;
    int b = 5;
    temp = a > b ? a : b;
  }
  etc.......
}

The inlining of a function can give a significant boost in performance if it is called repeatedly (e.g., inside a large loop). The penalty for inlining a function is that it might make the compiled code larger, which will cause the code to occupy more memory while it is running. For small functions that get called many times, that memory effect will be small whereas the potential performance gain might be large.

There are no simple answers to the question of whether inlining will improve the performance of your program. A lot depends on the optimization settings of the compiler. A lot depends on the nature of the program. Does it make heavy use of the processor? Does it make heavy use of system memory? Does it spend a lot of its time interacting with slow devices (e.g., input and output)? The answers to these questions affect the answer to the question of whether to inline, and we leave that to a more advanced treatment of the subject. For an overview of the complexity of this issue, visit Marshall Cline's FAQ Lite site.

An inline function is similar to a #define macro with one important difference: The substitution process for a #define macro is handled by the preprocessor, which is essentially a text editor. The substitution process for an inline function is handled by the compiler, which will perform the operation much more intelligently with proper type checking. We discuss this in more detail in Section 5.10.1.