Inline Function

When you inline a function, the complete body of a function is inserted for each occurrence of the selected function.

Watch a demo of this feature here.

Implementation notes

  • When you select the definition of a function, the function is removed from the source file, and every call to this function is replaced with the function body.
  • When you select a call to a function, only this call is inlined, and the function definition is left unchanged.
  • The parameters and local variables of a function are renamed during substitution.

Limitations

  • Only inline and static functions are supported.
  • You can't inline:
    • recursive functions
    • functions with more than one return statement
    • functions referenced by address

Example

static int foo(int a) {			  
    int b = a + 2;				    
    return b;				      
}						  
int main() {				      
    int c;					     
    c =  foo(1) ;				 
    return c; 
} 

In this example, we can inline 'foo'.

Result

int main() { 
 int c;
  int a = 1;int b = a + 2;c = b; 
 return c;
}

Can't inline function declared in system header

You'll see this message if the function definition is found in the system header.

For example, this message will occur if there's an attempt to inline 'pow' from 'math.h' in the snippet below:

#include <iostream>
 #include <stdio.h>
 #include <math.h>
 
 using namespace std;
 
 #define PI 3.14
 
 static float getArea(float radius) {
   float area = PI * *pow(radius, 2)*;
   return area;
 }

Can't inline function: This function is invoked using its fully qualified name

You can inline a function if it is called directly from another class member, but you'll trigger this message if you attempt to inline functions such as 'x->foo()' or 'x.foo()' in the situations noted below:

 class A{
    void foo() {...}
    void abc();
 }
 void A::abc()
 {
    foo(); //we can inline this
 
    A::foo(); //we can't inline this
    A x = new A();
    x->foo(); //we can't inline this
 }