What is the usage of the ‘inline’ keyword in C++?

In C++, ‘inline’ is a keyword used to suggest the compiler to insert the code inside a function directly at the place of function call, rather than executing the function call. This can improve the program’s efficiency.

Functions that use the inline keyword are known as inline functions. Inline functions are typically defined in header files so they can be used in multiple source files. When compiling, the compiler often inserts the code of inline functions directly where they are called, instead of generating a function call.

Functions using the inline keyword have the following characteristics:

  1. The function body typically contains only simple code.
  2. Functions are typically called frequently.
  3. Loops or recursion are typically not found within the function body.
  4. There are typically no complex control flows (like switch statements) within the function body.

The advantage of using functions with the inline keyword is:

  1. Improve the efficiency of the program by avoiding the overhead of function calls through inlining the code directly at the call site.
  2. Avoiding the overhead of creating and destroying stack frames caused by function calls.

It is important to note that the inline keyword is simply a suggestion to the compiler, whether or not the function is treated as an inline function depends on the compiler’s implementation. If the function body is too complex or the compiler deems it unsuitable for inlining, the compiler may ignore the inline keyword.

In C++, it is common to place both the definition and declaration of functions in the header file, and declare the functions as inline, so that they can be used in multiple source files. This helps prevent conflicts in defining the same function in multiple source files.

bannerAds