Inline Functions In C++ - C++ Programming Tutorial
C++ Course / Functions / Inline Functions In C++

Inline Functions In C++

BLUF: Mastering Inline Functions In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Inline Functions In C++

C++ is renowned for its efficiency. Learn how Inline Functions In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, an inline function is a function that gets defined by using the inline keyword. Within the inline function, the compiler substitutes the function call with the initial code of the function at compile time. The primary objective is to boost the program's performance by minimizing the overhead associated with function calls.

Inlining a function can optimize code performance by inserting the function's code directly at each function call. When modifications are applied to an inlined function, recompilation is necessary to ensure all instances of the function's code are updated. Failing to do so may result in the program retaining outdated functionality.

Syntax

It has the following syntax:

Example

inline return_type function_name(parameters)  

{  

   // Function Code  

}

In this syntax,

  • Inline: It is used to define that the function is an inline. It also tells to the compiler to the compiler to include the code of the function directly where it is called in the program.
  • data_type: It is used to define the define the return type of the function.
  • function_name: It is used to define the function name that is mainly used to call the function.
  • Parameters: It is used to define the list of parameters that the function takes.
  • Simple C++ Addition Program using Inline Function

Let's consider a scenario where we are adding numbers using an inline function in C++.

Example

Example

#include <iostream>  

using namespace std; //using standard namespace

inline int add(int a, int b) //inline function

{  

    return(a+b);  

}  

int main() //main function  

{  

    int a, b; //declaration of integer a and b 

    cout<<"Enter the Value of A: ";

    cin>> a;

    cout<<"Enter the Value of B: ";

    cin>> b;

    cout<<"Addition of 'a' and 'b' is: "<<add(a, b); //print the addition of a and b

    return 0;  

  

}

Output:

Output

Enter the Value of A: 15

Enter the Value of B: 35

Addition of 'a' and 'b' is: 50

Explanation:

In this instance, we are examining an inline function that operates on two integer variables, namely int a and int b. Subsequently, the function computes and returns the sum of a and b. Within the main function, the user is prompted to input the values for a and b. Following this input, the inline function is invoked to calculate and display the sum of a and b.

Why do we need an inline function in C++?

In C++, one of the primary purposes of utilizing an inline function is to minimize the overhead associated with function calls, thereby enhancing the code's execution speed. Each time the function is invoked, considerable time is taken to execute tasks like transitioning to the calling function.

If the function is short in length, the additional processing can sometimes exceed the time taken for the function's actual execution. When employing an inline function, the compiler aims to substitute the function call with the function's actual code during compilation, removing the need for a separate function call and conserving time and memory in such scenarios.

We cannot provide the inlining to the functions in the following circumstances:

  • If a function is recursive.
  • If a function contains a loop like for, while, do-while loop.
  • If a function contains static variables.
  • If a function contains a switch or go-to statement
  • When do we require an inline function?

An inline function can be used in the following scenarios:

  • An inline function can be used when the performance is required.
  • It can be used over the macros.
  • We can use the inline function outside the class so that we can hide the internal implementation of the function.
  • C++ Multiplication Program Using Inline Function

Let's consider a basic multiplication scenario utilizing the inline function within C++.

Example

Example

#include <iostream>

using namespace std;  // Using standard namespace

inline int multi(int a, int b) //initialization of inline function

{  

    return a * b;  //returns the product of a and b

}  

int main()  //main function

{  

    int a = 5, b = 8;  //Declaration and initialization of two integers

    // Calling the inline function multiple times

    cout << "The Multiplication of a and b: " << multi(a, b) << endl; 

    cout << "The Multiplication of a and b: " << multi(10, 15) << endl;     

    cout << "The Multiplication of a and b: " << multi(15, 20) << endl;     

    return 0; 

}

Output:

Output

The Multiplication of a and b: 40

The Multiplication of a and b: 150

The Multiplication of a and b: 300

Explanation:

In this instance, we are examining an inline function that operates on two integer variables, namely int a and int b. The function calculates the product of a and b. Within the main function, we declare and assign values to variables a and b. Subsequently, the inline function is invoked several times, and the resulting values are displayed.

Inline Function in Class

In C++, every member function declared within the class is automatically considered inline by the compiler. When it's necessary to explicitly specify a function as inline and it's being defined outside the class, the inline keyword must precede the function definition.

Square of a Number Example using Inline Function in Class:

Let's consider an illustration to calculate the square of a specified number by employing an inline function within a Class.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class CppTutorial{

public:

	inline int square(int a); //declare inline

};

inline int CppTutorial::square(int a) // Define the function

{

	return a*a;

}

int main() //main function

{

	CppTutorial obj;

	cout <<"The Square of a Number is: "<<obj.square(10);

	return 0;

}

Output:

Output

The Square of a Number is: 100

Explanation:

In this instance, we've selected a class named CppTutorial which defines an inline member function named square(int a). Within the main function, an instance of the class is instantiated, and the square method is invoked with the argument 10.

Difference between Inline and Macro

Several variances between Inline and Macro in C++ are outlined below:

Features Inline Functions Macros
Definition These are specified using the inline keyword. These are specified using the #define pre-processor directives.
Expansion These are expanded by the compiler. These are expanded by the pre-processor.
Scope These functions have scope and type checking such as regular functions. These functions have no scope or type checking.
Debugging These are easy to debug because they are executed during the compile time. These are complex to debug because these are not executed during compile time.
Private Members Inline functions can access private members of a class. These can never access the private members of a class.
Evaluation All the parameters of inline functions are evaluated for single time. When the macro is used in the code, parameters are evaluated multiple times.
Error Checking In inline functions, errors are checked by the compiler. In Macros, errors are not detected properly.
Usage It is suitable for small functions. It is mainly used for constants.
Recursion These functions can call themselves recursively. These cannot be recursive.

Advantages and Disadvantages of Inline Function

Various benefits and drawbacks of inline functions in C++ are outlined below:

Advantages:

  • In the inline function, we do not need to call a function, so it does not cause any overhead.
  • It also saves the overhead of the return statement from a function.
  • It does not require any stack on which we can push or pop the variables because it does not perform any function calling.
  • An inline function is suitable for embedded systems because it yields less code than a normal function.
  • Disadvantages:

  • The variables that are created inside the inline function will consume additional registers. If the variables increase, the use of registers also increases, which can increase the overhead on register variable resource utilization. It means that when the function call is replaced with an inline function body, then the number of variables also increases, which leads to an increase in the number of registers.
  • If we use many inline functions, the binary executable file also becomes large.
  • The use of so many inline functions can reduce the instruction cache hit rate, which reduces the speed of instruction fetch from the cache memory to that of the primary memory.
  • Sometimes, inline functions are not useful for many embedded systems because the size of the embedded is considered more important than the speed.
  • It can also cause thrashing due to the increase in the size of the binary executable file. If the thrashing occurs in the memory, it leads to the degradation in the performance of the computer.
  • Conclusion

In summary, inline functions accelerate program execution by inserting function code directly, eliminating the typical call overhead. This approach minimizes the need to push and pop variables onto the stack, resulting in more streamlined code execution. The primary objective is to optimize program performance by minimizing function call overhead.

C++ Inline Function MCQs

  1. Which one of the following keywords is used to declare an inline function in C++?
  • in_function
  • inline
  • fast
  1. Which one of the following statements shows a correct difference between Inline and Macros Functions?
  • Macros are expanded before compilation.
  • Inline functions cannot return values.
  • Macros are type-checked.
  • Inline functions are expanded by the pre-processor.
  1. Which of the following options is correct about inline functions in C++?
  • They are ensured to be inlined by the compiler.
  • They can never be recursive.
  • They always decrease the size of the executable.
  • They enhance performance by avoiding the function call overhead.

Option d) improves efficiency by circumventing the overhead of function calls.

  1. What is the expected result of the subsequent code?
Example

#include <iostream>

using namespace std; //using standard namespace

inline void myfun();

int main() //main function

{

    myfun();

    return 0;

}

inline void myfun()

{

    cout << "Hello Logic </> practice World!";

}
  • Syntax Error
  • Runtime Error
  • Hello Logic </> practice World!
  • Linker Error
  1. What will the result be when running the given C++ code?
Example

#include <iostream>

using namespace std; //using namespace standard

class Inline_exm {

public:

    inline void myfun();

};

void Inline_exm::myfun() inline

{

    cout << "Hello Logic </> practice World!";

}

int main() //main function

{

    Inline_exm Inl;

    Inl.myfun();

    return 0;

}
  • Syntax Error
  • Hello Logic </> practice World!
  • Logical Error
  • Runtime Error

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience