Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Inline Function in C++

Back to home
Logicmojo - Updated Jan 11, 2023



Memory preservation is one of the main reasons to use functions in programmes, especially when those functions are likely to be called repeatedly. When a function is called, activities like shifting to the function call take a while to complete.
The time it takes to jump to the calling function may be longer than the time it takes to run that function if a function is short, as overheads might eat up a large portion of its execution time.
One of the answers to this problem is macro definitions, sometimes known as macros.

In 2023 for C++ language, this issue is tackled in a different way. To cut down on the time it takes to call short functions, C++ adds a new function called the inline function.
This article updated on 2023 will give the reader an overview of inline functions in C++, a crucial area of programming, and then show them in action.

What is Inline function in C++

Similar to how macros in C reduce programme execution time, inline functions are an optimization feature in C++. When managing classes in C++, this idea of inline functions is applied. But it is also applied in other contexts. The compiler substitutes it with a copy of that function's code whenever such a function is found (function definition). To put it another way, one may say that a function like this is enlarged in-line, hence the name inline function.
When a programme calls a function multiple times and the definitions are brief, inline functions are frequently employed. It takes less time to move programme control from the calling function to the definition of the called function when inline functions are used.

To the compiler, inlining a function is only a request or a suggestion—it is not a requirement. The compiler will decide whether to accept or reject this recommendation to inline a certain function. Under some of the following conditions, the compiler is most likely to disregard the inlining of a function:

      ⮞ The compiler does not comply with the programmer's request to make a function with a return statement that is marked as inline and without returning any value an inline function.

      ⮞ The compiler rejects the inline recommendation when a programmer tries to inline a function that has a loop (for, while, or do-while).

      ⮞ Recursive functions are unable to be inlined.

      ⮞ It is not possible to convert a function with static variables into an inline function.

      ⮞ If a function requests to be inlined but contains switch or go-to statements, the compiler rejects the request.

Syntax

inline return_type function_name(parameters){
    // function code
}  

Let's take an example

#include <iostream>

using namespace std;

inline int subtract_func(int x, int y) {
  return x - y;
}
inline int add_func(int a, int b) {
  return a + b;
}

// Main function
int main() {
  cout << add_func(1, 11) << endl;
  cout << subtract_func(100, 75) << endl;
  return 0;
}


What is the issue with macros

Readers who are familiar with the C programming language are aware that it uses macros. All macro calls are directly replaced by the preprocessor in the macro code. It is advised to use inline functions rather than macros whenever possible. Dr. Bjarne Stroustrup, the man behind C++, claims that because macros are error-prone and rarely essential in C++. The use of macros in C++ has significant drawbacks. Private members of a class are inaccessible to macro. Although macros appear to be function calls, they are not.

#include <iostream>
using namespace std;
class func
{
	int x;
public:
#define MAC(func::x) // error
};

The C++ compiler verifies that the necessary conversions are made and that the inline functions' parameter types are valid. A preprocessor macro cannot accomplish this. Additionally, the preprocessor manages macros, while the C++ compiler manages inline functions.
Recall: While it is true that all functions specified inside a class are implicitly inlined and that the C++ compiler will call them inline, inlining cannot be done if the function is virtual. This is due to the fact that calls to virtual functions are resolved at runtime rather than at compile time. If the compiler doesn't know which function will be called, how can it conduct inlining? Virtual implies to delay action until runtime, and inlining means to act immediately after compilation.

If the function is not expanded inline, the compiler may provide a warning, depending on the one you are using. Inline functions are not supported by programming languages like Java and C#.
However, because final methods cannot be altered by subclasses and calls to final methods are resolved at compile time in Java, the compiler can execute inlining when the small final method is called. By inlining short function calls, the JIT compiler in C# can also optimise code (like replacing body of a small function when it is called in a loop).

When to use inline function

As needed, we can use the inline function. Here are a few suggestions that could be helpful:
The inline function can be used when performance is required.
In place of macros, we can utilise the inline function.
To hide function implementation specifics, we prefer to utilise the inline keyword outside of the class with the function definition.

Things to keep in mind when utilising Inline functions

      ⮞ Small inline functions must be maintained since they perform better and are more effective.

      ⮞ Although turning all functions into inline functions does boost performance, we shouldn't do so. Because moving huge functions intoline could result in code bloat and a reduction in efficiency.

      ⮞ It is advised to declare huge functions outside the definition of a class using the scope resolution:: operator because, if defined inside the definition of a class, they may become inlined automatically, which would again reduce the efficiency of our code.

Advantages of Inline function

These are a few of the factors that will motivate you to use this function in your programmes.

      ⮞ Since there are no overhead calls, the application runs more quickly.

      ⮞ The overhead of pushing and removing variables from the stack during function calls is avoided by the function.

      ⮞ A C++ inline function reduces the overhead of the return call.

      ⮞ Program execution can be sped up by storing the inline function in a header file to save time.

      ⮞ Utilizing the instruction cache increases the locality of reference. The speed of CPU-bound applications improves as the number of cache lines utilised to hold the code reduces, pushing it to execute faster.

Drawbacks of C++'s inline function

      ⮞ It will make the executable larger for lengthy code.

      ⮞ A simple modification in the inline code will require you to recompile everything because the inline function is called at compilation time.

      ⮞ Excessive C++ inline functions might slow down the speed at which instructions are transferred from the instruction cache to primary memory.

      ⮞ Program execution can be sped up by storing the inline function in a header file to save time.

      ⮞ Inline functions might not be included in embedded systems since code size is more significant than speed.



Learn More

Classes and functions that can be used inline

The class itself can define the inline method as well. In actuality, all of the class's specified functions are implicitly inlined. Therefore, all restrictions that are applicable to inline functions are also applicable here.
If you must explicitly declare an inline function in a class, do it there before using the inline keyword to specify it outside of the class.

Let's see an example

class x
{
public:
	inline int square(int x) {

	}
};

The method mentioned above is thought to be a poor programming method.
The most effective programming approach is to write the function prototype inside the class and declare it as an inline in the function specification.

class x
{
public:
	int square(int x); 
};

inline int X::square(int x) 
{

}

#include <iostream>
using namespace std;
class Math_riddle
{
	int x,y,plus,subtract,mult;
	float divi;
public:
	void getValue();
	void add();
	void sub();
	void mul();
	void div();
};
inline void Math_riddle :: getValue()
{
	cout << "Enter first value:";
	cin >> x;
	cout << "Enter second value:";
	cin >> y;
}

inline void Math_riddle :: add()
{
	plus = x+y;
	cout << "add of two numbers: " << x+y << "\n";
}

inline void Math_riddle :: sub()
{
	subtract = x-y;
	cout << "Difference of two numbers: " << x-y << "\n";
}

inline void Math_riddle :: mul()
{
	mult = x*y;
	cout << "Product of two numbers: " << x*y << "\n";
}

inline void Math_riddle ::div()
{
	divi=x/y;
	cout<<"div of two numbers: "<<x/y<<"\n" ;
}

int main()
{
	cout << "Program using inline function\n";
	Math_riddle m;
	m.getValue();
	m.add();
	m.sub();
	m.mul();
	m.div();
	return 0;
}


Important Notes

Here are a few key elements concerning inline functions that should be kept in mind when utilising the C++ language as an overview of the entire issue of inline functions.

      ⮞ Inline functions are not required; they are merely recommendations. The compiler might not inline the routines that the programmer marked as inline. In addition, even if a function is not designated as inline, the compiler may nevertheless choose to inline it.

      ⮞ Since they are already considered to be inline functions by default, functions that are declared and defined inside of a class do not need to be explicitly defined as such.

      ⮞ Inline works as a compiler controlled copy and paste action and is not implemented forcibly, which makes it easier to debug than pre-processor macros and ensures that the namespaces and code are not corrupted.

      ⮞ Virtual methods cannot be inlined until the compiler is aware of the object's type, which occurs when the object is defined and built within the same function body.

      ⮞ A method or function is not immediately inlined only because it is used as a template in the header section.

Inline Function Vs Normal Function

Inline FunctionNormal Function
When it is activated, it expands inline.It is a feature that gives the programme modularity.
It is typically employed to lengthen the program's execution time.It is typically used to make code more manageable and more reusable.
It is essentially a function that is used for small, often called functions.In essence, it is a collection of statements that work together to do a specific job. It is employed during large functions.
It demands the term "inline" in its declaration.No keyword is necessary in its declaration.
Typically, it operates significantly more quickly than regular functions.For small size functions, it typically executes more slowly than an inline function.
This minimises the time it takes to search the body of functions on the storage device or hard disc by copying the body of functions to every context where it is utilised.The function's body is kept on the storage device in this case, and each time the function is called, the CPU must load the function's body from the hard drive into RAM for execution.
Every time the function is called during compilation, the compiler always inserts a duplicate of its code there.Such functionality is not offered by it.
It typically just contains 2-3-line codes.When there are a lot of line codes, standard functions typically contain a lot of code.
In comparison to regular function, it is a little more challenging to comprehend and test.In comparison to the inline function, it is considerably simpler to comprehend and test.
Classes that include functions are implicitly inlined.Ordinary functions are those that exist outside of a class.
In comparison to regular function, it is a little more challenging to comprehend and test.In comparison to the inline function, it is considerably simpler to comprehend and test.
Too many inline functions increase file size because they duplicate code during compilation.Too many common functions after compilation have no impact on file size.


Inline Function Vs Macros

Inline FunctionMacro
The compiler parses inline routines.The preprocessor increases the size of macros.
Either within or outside of the class can define it.The programme always begins with it defined.
It only once evaluates the argument.Every time the argument is used in the code, it is evaluated.
All of the functions might not be expanded and inlined by the compiler.All macros are expanded.
The class's short functions that are defined immediately become inline functions.It is important to define macros specifically.
The class's data members can be accessed through an inline member function.Macros are unable to access class members' data and are never allowed to be class members themselves.
The curly brackets at the end of the inline function mark the end of the definition of the function.A new line begins the macro definition's conclusion.
An inline function is simple to debug because error checking is done during compilation.Macro debugging gets challenging because compilation does not include error checking.
Due to the function body beginning and ending in curly brackets, an inline function binds all the statements in the body very effectively.When a macro has several statements because it lacks a termination symbol, it encounters the binding problem.


FAQs

What distinguishes inline functions in C++ from normal functions and why are they necessary?

The control is often sent from the calling application to the called function during a function call.
Following programme execution, the called function hands back control to the caller programme along with a return value.
Because the function can be called at any desired point in the programme, rather than having to write the same code many times, this concept of function saves programme space.
This could be useful for shrinking the size of the programme, but it definitely lengthens the time it takes to run as the function must be called each time control is passed to it before returning a value.

This is highly helpful for large functions, but for minor functions, a user might want to explicitly insert the function definition code in the called position to speed up execution.
To reduce the overhead of function calls, C++ offers inline functions. In order to eliminate function calls, the compiler creates a copy of the function's code each time it is called.

Conclusions

This concludes our discussion of "Inline Function in C++." I sincerely hope that you learned something from it and that it improved your knowledge. You can consult the C++ Tutorial if you want to learn more about C++.

Good luck and happy learning!