Inline Function in C++ with Example


One of the main objectives of using functions in a program is to save time and memory space (by avoiding code repetition) which becomes appreciable when a function is likely to be called many times.

If we use inline functions, the compiler replaces the function call with the corresponding function code similar to macros. Inline functions are similar to macros. However, they provide better type checking & deal well with macros.

The syntax for inline functions:

inline <return value-type> <function name> (parameter list) { function body }

Few more points on inline functions

  • If functions are defined within the class, then they are automatically inline (implicit inline functions).
  • Inline functions are best used for small frequently used functions.
  • All inline functions must be defined before the functions call because the C++ Compiler has to put the code in the function body directly inside the code in the calling program.

Some compilers treat an inline function as a normal function if the inline function definition constants:

  • loops
  • switch-case
  • recursion
  • static variable etc.

Inline Function in C++ with Example

#include<iostream> using namespace std; inline float sum(float a, float b){ return a+b; } int main(){ float s; s = sum(4.6f, 9.2f); cout<<"The sum is"<<s<<endl; return 0; }

Output:-

The sum is :13.8

Explanation of the program

In this program, sum() is the inline function. During execution, the value of a becomes 4.6 and value of b become 9.2. The of the 2 variables is the value of s since that is the value returned by the sum() function.