When working with a programming language, we can use several methods to optimize the code and enhance a program’s performance. For example, in the C language, the Macro function is used to reduce the program’s execution time. Since C++ is an extension of C, it also provides a function called the inline function, which can speed up a program by reducing the execution time. 

In this article, we will discuss all the important concepts that are required to have an in-depth understanding of the inline function in C++.  This article covers all aspects of the inline functions that can be used to enhance a program’s performance and efficiency.

Inline Function in C++

C++ programming language provides various important and fascinating methods and in-built functions to its users. When it comes to enhancing the performance of the program, the inline function proves to be an excellent concept. Inline function in C++ is an enhancement feature that improves the execution time and speed of the program. The main advantage of inline functions is that you can use them with C++ classes as well. 

When an instruction of a function call is encountered during the compilation of a program, its memory address is stored by the compiler. The function arguments are copied on the stack and after the execution of the code, the control is transferred to the calling instruction. This process can sometimes cause overhead in function calls, especially if the function is small and its execution time is less than the switching time. This issue is resolved by using the inline functions. These functions overcome the overhead and also make the program faster by reducing the execution time of the program.

In case of inline functions, the compiler does not go through the above process of switching between the stack and calling function. Instead, it copies the definition of the inline function and the calling instruction with that definition. The following demonstration illustrates the working of inline function in C++:

// define an inline function

// that prints the sum of 2 integers

inline void printSum(int num1,int num2) {

    cout << num1 + num2 << "\n";

}

int main() {

    // call the inline function

    // first call

    printSum(10, 20);

    // second call

    printSum(2, 5);

    // third call

    printSum(100, 400);

    return 0;

}

The following diagram illustrates how the compiler works while executing the above program with inline function:

Inline_Function_in_Cpp

Following are some key points that you need to keep in mind while dealing with inline functions:

  • Inline functions that are small have higher efficiency and better results than the lengthier inline functions. So, try to keep your inline functions small in length.
  • Although these functions increase the efficiency of the program and improve its execution, you should not convert all the functions into inline functions. If you convert larger functions to inline, it may lead to code bloat and reduce the functioning quality of the program.
  • Always try to define large functions outside the class, since functions defined inside a class are automatically defined as inline and this will affect the program negatively. You can use scope resolution (::) for this purpose.

Also Read: The Easiest Guide to Understand Basic Concepts of C++

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Circumstances Where the Compiler Does Not Consider Inline Functions 

Inlining a function is not mandatory. It should be considered to be just a request, and it’s execution totally depends on the compiler. The compiler decides whether to accept or decline the request of inlining the function based on some circumstances as discussed below:

  • The compiler denies the request to make a function an inline function if it contains a return statement but does not return anything.
  • All those functions that contain a loop statement (for loop, while loop, or do-while loop) can not be considered as an inline function by the compiler.
  • The compiler will not consider a function to be an inline function if it is recursive.
  • If the function contains one or more static variables, the compiler will deny the request to make it an inline function.
  • If the function contains a switch or a go-to statement, the compiler will deny the suggestion to make it an inline function.

Syntax of Inline Function in C++

The syntax for defining the function inline is:

inline return_type function_name(data_type arg1 , data_type arg2 )

{

    // definition of the function

}  

Syntax explanation:

  • Keyword “inline”: The keyword inline is specified at the beginning to tell the compiler that the function is an inline function. However, it’s up to the compiler to decide whether to inline a function or not.
  • Defining the function: An inline function needs to be defined when it is declared. Whenever there is a call to the function in the program, the compiler will simply replace it with the function’s definition. 

The following example illustrates how to define an inline function in C++:

// an inline function to calculate

// smallest of 2 integers 

// and returns the result

inline int smallest( int num1 , int num2 ) {

   if( num1 < num2 )

      return num1;

   return num2;

}

Examples of Inline Functions in C++

The following examples illustrate the concept of inline function in C++:

Example 1

#include<iostream>

using namespace std;

// define an inline function

// using the keyword "inline"

inline int setNum()

{

    return 10; // definition of inline function 

}

int main()

{

    int num ; 

    // call the inline function

    num = setNum();

    // setNum() will be replaced by 

    // definition of inline function   

    cout << " The inline function returned: " << num  ;

    cout << "\n\n"; 

    return 0 ;

}

Inline_Function_in_Cpp_Ex_1.

Explanation of the Program

In the above program, the function setNum() is declared as an inline function using the keyword “inline”. This function simply returns an integer. When a call to this inline function is made, the compiler replaces the calling statement with the definition of the inline function setNum(). 

Instead of storing the memory address of the instruction and going through the process of loading the called function into the memory, the function’s definition is directly replaced at the calling instruction. So, in the instruction, num = setNum(), setNum() is replaced by 10, and 10 is stored in the variable num.

Example 2

#include<iostream>

using namespace std; 

// define an inline function

// to calculate the area of a rectangle

inline int area(int length, int breadth)

{

    return length * breadth ; 

}

int main()

{

    int length, breadth, result;

    cout <<  "Enter the length of the rectangle: ";

    cin >> length; 

    cout <<  "\nEnter the breadth of the rectangle: ";

    cin >> breadth; 

    // call the inline function (i.e. area())

    result = area(length , breadth);

    // this will be replaced by the

    // definition of the inline function 

    cout <<  "\nThe area of the rectangle is: " << result; 

    cout << "\n\n";

    return 0 ;

}

Inline_Function_in_Cpp_Ex_2.

Explanation of the Program

In the above program, the inline function area() accepts two integers- length, and breadth and returns the area of a rectangle. The program takes two integers as input from the user. When the function call to the inline function area() is made, the compiler copies the code inside the function and inserts it in the main(). So, the instruction result = area(length, breadth) will be converted to result = 2 * 4 during the compilation of the program.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example 3

#include <iostream> 

#include<cmath>

using namespace std;  

// define an inline function 

// to calculate square root of a number

inline float squareRoot(int num) 

    return sqrt(num); 

}  

// define an inline function 

// to calculate square of a number

inline int square(int num) 

    return num * num; 

int main() 

    int num = 9; 

    cout << "The square root of " << num << " is: ";

    // calling inline function squareRoot()

    cout << squareRoot(num) << "\n";  

    cout << "The square of " << num << " is: ";

    // calling inline function square()

    cout << square(num) << "\n\n"; 

    return 0; 

}  

Inline_Function_in_Cpp_Ex_3

Explanation of the Program

In the above program, two inline functions squareRoot() and square() are defined that return the square root and square of a number. When inline functions are called, the compiler makes the following changes during the compiling of the program:

squareRoot(num) is replaced by sqrt(9) and square(num) is replaced by 9 * 9.

When to Use the Inline Function?

Inline functions are very efficient and can be used in various areas of a program. But there are some cases where you can utilize the maximum features of these functions and extract the maximum output from them. Some of these cases are:

  • Inline functions can be used over macros. These functions are more efficient and optimized than macros and have an upper hand over them. You can get almost all the features that macros can provide by using inline functions.
  • Inline functions prove to be the best when it comes to performance. If you need the performance in your program, you must go with inline functions as they enhance the execution time and speed of your program.
  • If you want to hide the implementation details of your functions, you can define the inline functions outside the class by using the inline keyword.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Inline Functions Vs Macros

The following comparison chart highlights the major differences between the inline functions and macros.

Inline Functions

Macros

Inline functions are expanded by the compiler.

Macros are expanded by the preprocessor.

They are defined by the keyword inline.

They are defined by the keyword #define.

They can be defined within the class as well as outside the class.

They must be defined at the start of the program.

These functions can access the data members of a class.

Macros can never access the data members of a class.

All the parameters are evaluated just one time.

In Macros, parameters are evaluated each time the macro is used in the code.

They can be easily debugged as they are executed during compile time.

They can not be debugged easily because they are not executed during compile time.

Functions that are short in length are automatically declared as inline functions.

Macros have to be defined specifically.

They are less commonly used in the program.

They are more commonly used in the program, especially in competitive programming.

Just like other functions, these functions can also be terminated using a closing curly brace ( } ) at the end of the code.

Macros do not have any special symbol for termination. They get terminated after entering the next line.

Inline Function and Classes

C++ also allows you to declare the inline functions within a class. These functions need not be explicitly defined as inline as they are, by default, treated as inline functions. All the features of inline functions also apply to these functions. However, if you want to explicitly define the function as inline, you can easily do that too. You just have to declare the function inside the class as a normal function and define it outside the class as an inline function using the inline keyword.

Let us see the practical implementation of how we can define a function as an inline function explicitly:

class Example

{

public:

    inline int func(int n) // unnecessary use of inline

    {

        // this function is defined as an 

        //inline function by default 

    // function body    

    }

};

The above implementation is considered to be the wrong or bad style of coding since we are making unnecessary use of inline keywords. The below implementation is optimized, and good practice of defining an inline function explicitly:

class Example

{

public:

    int func(int n); // function declaration inside the class

};  

inline int n::func(int n) // defining the function as 

                          // inline using inline keyword  

}

The following program illustrates the concept of classes and inline function in C++:

#include <iostream>

using namespace std; 

// a class to find the area

class findArea

{

public: 

    // declare functions

    // (implicitly inline functions)

    void circle(int radius);

    void square(int side);

    void triangle(int base, int height);

    void rectangle(int length, int breadth);

};

// define the inline functions

// outside the class, using the 

// scope resolution operator (i.e. ::) 

// function to find the area of a circle

inline void findArea :: circle(int radius)

{

    cout << "The area of the circle is: ";

    cout << (3.14 * radius * radius) << "\n";

// function to find the area of a square

inline void findArea :: square(int side)

{

    cout << "The area of the square is: ";

    cout << (side * side) << "\n";

// function to find the area of a triangle

inline void findArea :: triangle(int base, int height)

{

    cout << "The area of the triangle is: ";

    cout << (0.5 * base * height) << "\n";

}

// function to find the area of a rectangle

inline void findArea :: rectangle(int length, int breadth)

{

    cout << "The area of the rectangle is: ";

    cout << (length * breadth) << "\n";

}

 int main()

{

    cout << "Inline function with classes program\n\n";    

    // create an object of the class

    findArea A;

    // call the inline functions

    A.circle(2);

    A.square(5);

    A.triangle(3, 4);

    A.rectangle(10, 12); 

    cout << "\n\n"; 

    return 0;

}

Inline_Function_in_Cpp_Ex_4 

Explanation of the Program

In the above program, a class findArea is defined and 4 functions are declared in the class. Note that these functions are implicitly inline functions, so there is no need to use the keyword inline here. However, to define these functions outside the class as inline, the scope resolution operator is used. When a call to these functions is made using an instance of the class, the compiler copies and replaces the definition of these functions. For example:

    A.circle(2)

    is replaced by 

    cout << "The area of the circle is: ";

    cout << (3.14 * radius * radius) << "\n";

In the same way, other function calls are also modified by the compiler during compilation.

Advantages of Inline Function in C++

  • The compilation speed of the program gets increased since the inline functions prevent function call overhead. 
  • Inline functions that are small in length can be used in embedded systems as well since these functions yield lesser code than the function call and return.
  • These functions also prevent the overhead of function return calls.
  • They allow the compiler to perform some optimizations on the body of the function that is content-specific in nature. Such optimizations cannot take place for other function calls.
  • During the invoking or calling of the function, these functions prevent the overhead of push and pop stack variables. 

Disadvantages of Inline Function in C++

  • Inline functions must be short in length as lengthier inline functions can cause a reduction of the cache hit rate of the instructions. This can have adverse effects on the efficiency of the program.
  • Excess use of inline functions in the code may lead to the enlargement of the size of the binary executable code.
  • In the case of large functions, compilation overhead can take place and reduce the efficiency of the code.
  • Implementation of these functions in the header files can make them heavy.
  • Since storage is not allocated to such functions and they are stored in a symbol table, the compiler cannot perform the inlining of these functions, and hence you can not get the address of these functions.
  • Large inline functions are useless for embedded systems since these systems give preference to the size of the function over speed.

inline, __inline, and __forceinline

The inline, and __inline keywords specify that a copy of the function should be inserted in the code during the compilation of the program. However, these keywords only make a request which can be denied by the compiler. The compiler analyzes the program, and if the inlining is cost-efficient, only in that case the function is inlined, otherwise, the request is denied.

The __forceinline (as the name suggests) forces the compiler to inline a function, even if it is not cost-efficient as per the analysis of the compiler. This is completely based on the programmer’s choice and can sometimes provide performance gains. This keyword should be used with extreme caution as it can lead to poor performance. There are still some situations where even __forceinline cannot force the compiler to inline a certain function. 

C++ supports only the inline keyword. You can use the __inline, and __forceinline keywords in the C language.

Conclusion

In this article, we have learned about inline function in C++. The article starts with a basic introduction of the use and purposes of inline functions and how they can increase the overall efficiency of the program. Moving ahead, we discussed how the compiler compiles inline functions and a few circumstances where it doesn’t consider the inline functions. Further, we learned the syntax, parameters, saw a few examples, and also covered the advantages and disadvantages of inline function. We also saw the differences between macros and inline functions, and how we can use them with classes as well.

If you want to get a complete overview of the entire C++ programming language concepts, you can check out our article on C++ Programming for Beginners.

Check out our course on Full Stack Web Development if you want to learn a set of trending technologies and skills, and provide yourself a chance to work for top product-based companies giants. This course will walk you through all those technologies/skills that you will need to land your foot into professional web application development. These include DevOps, Agility, Java, CSS, HTML, AWS, etc.

You should also check out the complete list of free online courses by Simplilearn to skill yourself up. If you have any queries or suggestions for us, please mention them in the comment box and we will have our experts answer them for you as soon as possible.

Happy Learning!