Home > Blogs > 30 C++ Tips in 30 Days: Tip # 3 inline Do's and Don'ts

30 C++ Tips in 30 Days: Tip # 3 inline Do's and Don'ts

By  Nov 21, 2007

Topics: Programming, C/C++

Sometime in the late 1980s inline was a big shot. Today the best thing to do about this keyword is ignore it completely. Chances are high that your compiler and linker are smart enough to figure out by themselves which functions are better candidates for inlining and which ones aren't. Explicit inline declarations thus merely get in the compiler and linker's way. However, if you must use inline, there are some rules of thumb that will help you get the best out of this feature.

Implicit inline

In some cases, C++ implicitly declares a function as inline. All implicitly-defined member functions (e.g., implicitly defined constructor, destructor etc.) are inline. In addition, any function that's defined inside the class body is implicitly declared inline, regardless of whether an explicit inline specifier appears in the function's declaration.


Explicit inline

If you must use inline, always place it in the first declaration that compiler will see. For example, if you declare a member function in a class and then define that member function outside the class body, the in-class declaration must include an explicit inline in both places.  


Best and Worst inline Candidates

Paradoxically, the best candidates for inlining are functions that don’t really need the inline specifier, since the compiler will automatically inline them anyway. These include:

  • Accessor member functions (getters and setters which contain only a single return and assignment statement, respectively)
  • Functions with a small number of statements called from a loop
  • Functions that are stubs e.g., void func() {}

In contrast, functions that contain local static data, recursive functions, virtual functions and functions that have nested loops are usually poor inline candidates. In addition, functions whose address is taken are always poor inlining candidates, regardless of their implementation.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.