Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Inline Functions

C++ Inline Functions

C++ Classes & Objects C++ Classes & Objects

C++ Inline functionsare usually used together with classes. If a function is inline, then at compile time the compiler places a copy of the function's code at each place that calls the function.

Any modification to an inline function requires recompiling all clients of the function, because the compiler needs to replace all the code again; otherwise the old function will continue to be used.

To define a function as an inline function, you need to place the keyword before the function name inline, and define the function before calling it. If the defined function is more than one line, the compiler ignores the inline qualifier.

Functions defined within a class definition are all inline functions, even without using the inline specifier.

Below is an example using an inline function to return the maximum of two numbers:



#include 

 

using namespace std;



inline int Max(int x, int y)

{

   return (x > y)? x : y;

}



// Main function

int main( )

{



   cout << "Max (20,10): " << Max(20,10) << endl;

   cout << "Max (0,200): " << Max(0,200) << endl;

   cout << "Max (100,1010): " << Max(100,1010) << endl;

   return 0;

}

When the code above is compiled and executed, it produces the following result:



Max (20,10): 20

Max (0,200): 200

Max (100,1010): 1010

C++ Classes & Objects C++ Classes & Objects