How to Declare Inline Functions in C++

In C++, you designate a C++ function with the inline keyword to make a request to the compiler to improve the function's performance. Depending on several factors, the compiler may integrate the function's code into the caller's code stream and optimize the inline-expanded code. Inline is a request, not a guarantee. The cost of inlining is usually an increase in code size. Read on to learn how to declare inline functions in C++.

Things You'll Need

  • Intermediate understanding of C++ or C
  • C or C++ compiler with an IDE
Show More

Instructions

    • 1

      Make functions inline according to the following criteria. The code inside the function's braces shouldn't exceed three lines. The program's calls to the function should number in the hundreds or more. Keep in mind that overly zealous inlining can cause a phenomenon called code bloat. This means too much fetching into virtual memory, which can slow down performance.

    • 2

      Put the inline keyword before the function declaration and definition to designate that it's inline:

      inline void Func(int); // declaration

      inline void Func(int num){

      // 3 lines of code

      }

    • 3

      Inline the member function of a C++ class by writing the code of the function in the class body. This is an alternative way of telling the compiler to inline that function, but it has to be a member of a C++ class:

      class Complex {

      public:

      int Init() {

      // 3 lines of code

      }

    • 4

      Find alternatives to using the define macro, which is an alternative to an inline function. The define macro allows the preprocessor to inline-expand a function. Macros are unsafe, because they don't do type checking:

      #define avoidIfPoss(i) ( (i) >= 0 ? (i) : -(i) )

Tips & Warnings

  • This tutorial applies equally to C programming.

  • If you want to define a member function as inline using the keyword, put the keyword next to the definition outside the class body, not next to the declaration inside the class.

  • If your system has 100 functions, each defined by 10 bytes of executable code, and you call each function in 100 places in your program, this will increase your executable by 100,000 bytes.

  • Function inlining might increase the number of cache misses. A loop can access many lines of memory cache, which might cause the memory cache to thrash.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured