When do you use inline function in C++ project?

(Last Updated On: February 25, 2019)

Answer: In the following scenarios we should use inline functions in C++ programming.

When to Use Inline function in C++:

1) When the member functions are very small e.g. only returning value or having very small statements then we should use inline member function in C++ class. As they are not taking much space and avoid cost of function call.


2) If the small member functions (little bit larger than above example or same) have frequent call. e.g.



3) Code readability: very small functions are understandable itself and no need to put any comment about the function. At the same point declaration and definition we can understand what function is about e.g.



4) In some of the scenarios we have to make use of inline function in c++ program instead of MACRO as we may get undesired result with MACRO.

In below example, we are using MACRO and inline function doing the same job i.e. double the number passed.
We’ll be using the value of variable int a=2; and pass parameter as (++a) to both MACRO and inline function.
So, value of passing parameter will be 3 on increment and expected result from both MACRO and inline function would be square i.e. 9.
But with MACRO, we will be getting undesired result i.e.16 instead of 9 as MACRO, SQUARE (++X) expands to ++x * ++x, which will increment the value of x twice i.e. 4 and give the result equals 4*4 =16.
This problem will not occur in inline member function in C++ program.