Inline Function in C++ with example

In this tutorial, we will see a simple example of inline function in C++.

Inline functions in C++

Inline functions are treated differently by the compiler. So, they usually run more efficiently, although they consume more storage.

Calls to inline functions do not have the overhead of normal function calls. This is because the compiler replaces the function call with function definition at compile time instead of referring function definition at runtime.

Syntax of inline function in C++

We can make a function inline by using the reserved word inline before the function declaration.

inline return_type function_name (arguments)
//function body

Example showing how to use inline functions in C++

#include <iostream>
using namespace std;

// function to sqaure a number
inline int square(int i)
  return (i*i);

int main()
  int n, res;
  n = 5;
  res = square (n);
  cout << "Square of " << n << " is " << res;

In the above example, the function square is an inline function.


Square of 5 is 25

Useful points

  • The functions we define inside a class are by default inline functions.
  • Making a function inline is useful for small functions.
  • Do not use it when memory is a constraint.
  • Use when performance is needed.
  • Inline is preferred to macros.

Also read, Scope Resolution Operator(::) in C++
Cascading Member Functions in C++

Leave a Reply