Inline Functions
Table of Contents

Introduction

  • One major downside of functions is that every time is called, there is a certain amount of performance overhead that occurs.
  • The inline keyword is used to request that the compiler treat your function as an inline function.
  • A function specified as inline (usually) is expanded "in line" at each point in the program in which it is invoked. Unlike other function definitions, inlines should be defined in header files.

Whenever an inline function is added to or changed in a header file, every source file that uses that header must be recompiled.

Examples

Example 1

int min(int nX, int nY)
{
    return nX > nY ? nY : nX;
}
 
inline int min2(int nX, int nY)
{
  return nX > nY ? : nX;
}
 
int main()
{
    using namespace std;
    cout << min(5, 6) << endl;
    cout << min(3, 2) << endl;
 
    cout << min2(5, 6) << endl;
    cout << min2(3, 2) << endl;
 
    return 0;
}

When the program compiles main() it will create machine code as if main() had been written like this:

int main()
{
    using namespace std;
    cout << (5 > 6 ? 6 : 5) << endl;
    cout << (3 > 2 ? 2 : 3) << endl;
    return 0;
}
  • Inlining a function is best suited to short functions.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.