Inline Functions

C++ provides the inline keyword as a function qualifier. This keyword causes a new copy of the function to be inserted in each place it is called. If you call an inline function from 20 places in your program, the compiler inserts 20 copies of that function into your .EXE file.

Inserting individual copies of functions eliminates the overhead of calling a function (such as loading parameters onto the stack) so your program runs faster. However, having multiple copies of a function can make your program larger. You should use the inline function qualifier only when the function is very small or is called from few places.

Inline functions are similar to macros declared with the #define directive; however, inline functions are recognized by the compiler, while macros are implemented by a simple text substitution. One advantage of this is that the compiler performs type checking on the parameters of an inline function. Another advantage is that an inline function behaves just like an ordinary function, without any of the side effects that macros have. For example:

// A macro vs. an inline function

#define MAX( A, B ) ((A) > (B) ? (A) : (B))

inline int max( int a, int b )

{

if ( a > b ) return a;

return b;

}

void main()

{

int i, x, y;

x = 23; y = 45;

i = MAX( x++, y++ ); // Side-effect:

// larger value incremented twice

cout << "x = " << x << " y = " << y << '\n';

x = 23; y = 45;

i = max( x++, y++ ); // Works as expected

cout << "x = " << x << " y = " << y << '\n';

}

This example prints the following:

x = 24 y = 47

x = 24 y = 46

If you want a function like max to accept arguments of any type, the way a macro does, you can use overloaded functions. These are described in the section “Overloaded Functions”.

To be safe, always declare inline functions before you make any calls to them. If an inline function is to be called by code in several source files, put its declaration in a header file. Any modifications to the body of an inline function require recompilation of all the files that call that function.

The inline keyword is only a suggestion to the compiler. Functions larger than a few lines are not expanded inline even if they are declared with the inline keyword.

Note:

Microsoft C/C++ provides the __inline keyword for C, which has the same meaning as inline does in C++.