Inline Functions

An inline function is a function whose statements are embedded in the caller as a substitute for the function call. This avoids the overhead a context switch which must be performed whenever a function is called and whenever a function returns to the caller. The only purpose for inlining is to increase the execution speed of a program.

Inline functions should be small and simple. Since a function may be called from many different places in a program, inlining large functions can result in an undesirable increase in the size of a program. Inline functions should not contain any function calls or I/O statements. As a general rule, if a function has more than five statements it should not be inlined.

When you specify that a function is an inline function, it is merely a request of the compiler. The compiler may or may not actually inline the function.

Inlining Global Functions

To inline a global function:

Example:

   inline void swap(int &a, int &b)
   {
      int c = a;
      a = b;
      b = c;
   }

   int main()
   {
      int x = 5;
      int y = 10;
      swap(x,y);
      cout << x << "  " y << endl;
   }

Inlining Member Functions

There are two ways to inline a member function: implicit and explicit.

Implicit

In implicit inlining, the inline member function is defined within the class definition. The keyword inline is not used.

Example:

   class Date
   {
   public:
      Date(int mm,int dd,int yy) {month = mm; day = dd; year = yy;}
      void setdate(int mm,int dd,int yy)
                          {month = mm; day = dd; year = yy;}
      void showdate();  // not inlined

      // additional member functions

   private:
      int month;
      int day;
      int year;
   };

Explicit

In explicit inlining, the prototype in the class definition is preceded by the keyword inline. The member function defintion is defined outside the class definition, and is also preceded by the keyword inline.

Example:

   class Date
   {
   public:
      inline Date(int,int,int);
      inline void setdate(int,int,int);
      void showdate();  // not inlined

      // additional member functions

   private:
      int month;
      int day;
      int year;
   };

   inline Date::Date(int mm,int dd,int yy)
   {
      month = mm;
      day = dd;
      year = yy;
   }

   inline void Date::setdate(int mm,int dd,int yy)
   {
      month = mm;
      day = dd;
      year = yy;
   }

   void showdate()
   {
      cout << month << '/' << day << '/' << year;
   }


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2006