One of the main objectives of using functions in a program is to save some memory space, which becomes appreciable when a function is likely to be called many times. However, every time a function is called, it takes a lot of extra time in executing a series of instructions for task such as jumping to the function, saving register, pushing arguments into the stack, and returning to the calling function. When a function is small, a substantial percentage of execution time may be spent in such overheads.

One solution to this problem is to use macro definition, popularly know as macros. Preprocessor macros are popular in C. The major drawback with macro is that they are not really functions, and therefore, the usual error checking doe not occur during compilation.

C++ has a special solution to this problem. To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function. An inline function is a function that is expanded in line when it is invoked. That is, the compiler replaces the function call with the corresponding function codes. The inline function is defined as follows:

Example:

It is easy to make a function inline. All we need to do is prefix the keyword inline to the function definition. All inline functions must be defined before they are used.

Repeated code substituted in place of the function call.

We should take utmost care while making a function inline. The speed benefit of an inline function diminishes as it grows in size. At some point the overheads of the function call becomes small as compared to the execution of the function, and the benefits of inline function may be lost. In such a case, the use of normal function will be more meaningful. Normally only those functions are defined inline, which are only two or three lines big.

The keyword inline sends a request to the compiler to make the function inline and not a command.

There are few situations where an inline function may not work:

  • For a function returning values; if a return statement exists.
  • For a function not returning any values; if a loop, switch or goto statement exists.
  • If a function is recursive.

Example: Program to illustrate the working of an inline function.