inline function

inline function is a function which is expanded inline i.e. function definition is copied to a place where it is called.
When a function called in program, CPU does following:
a) Stores the address of instruction following the function call.
b) Push function arguments on the stack
c) Transfer the control to the function definition.
d) Execute the function
e) Transfer the control to the address stored at step a.

When execution time of function is less than the switching time from calling to called function, then this becomes overhead. To avoid this overhead, inline function is used.

For large/big function, this overhead does not matter because execution time is more than the switching time. Therefore, for large/big function, inline is not required.

By default, function defined inside the class is inline.

Not every inline function can be inline. It depends on compiler to make inline function inline or not i.e. inline function is a request to compiler not a command to a compiler.

Below is the criteria for inline function:
a) No Loops E.g. for, while, or do-while loop.
b) No switch or goto statement
c) No Static variables
d) Not a recursive function
If the any of the above criteria does not meet, then compiler may not inline the function.


#include <iostream>
using namespace std;
class test_inline
    unsigned int m_unsignedInt;
        m_unsignedInt = 0;
    inline int getNumber()
        return 5;
    void increment()  //by default, this is inline function.
        ++ m_unsignedInt; //This will be executed

Without using inline keyword also, the increment function is inline since it is defined inside the class and meets all the criteria of inline function i.e. inline keyword is not required if function is defined inside the class body.

inline functions are more than just replacement of function call with function definition. In the above increment function, getNumber is called which return one number but it doesn’t mean that next statement will not be executed.

Related posts