Inline function in C++
If make a function as inline, then the compiler replaces the function calling location with the definition of the inline function at compile time.
Any changes made to an inline function will require the inline function to be recompiled again because the compiler would need to replace all the code with a new code; otherwise, it will execute the old functionality.
Syntax for an inline function:
Let's understand the difference between the normal function and the inline function.
Inside the main() method, when the function fun1() is called, the control is transferred to the definition of the called function. The addresses from where the function is called and the definition of the function are different. This control transfer takes a lot of time and increases the overhead.
When the inline function is encountered, then the definition of the function is copied to it. In this case, there is no control transfer which saves a lot of time and also decreases the overhead.
Let's understand through an example.
Once the compilation is done, the code would be like as shown as below:
Why do we need an inline function in C++?
The main use of the inline function in C++ is to save memory space. Whenever the function is called, then it takes a lot of time to execute the tasks, such as moving to the calling function. If the length of the function is small, then the substantial amount of execution time is spent in such overheads, and sometimes time taken required for moving to the calling function will be greater than the time taken required to execute that function.
The solution to this problem is to use macro definitions known as macros. The preprocessor macros are widely used in C, but the major drawback with the macros is that these are not normal functions which means the error checking process will not be done during the compilation.
C++ has provided one solution to this problem. In the case of function calling, the time for calling such small functions is huge, so to overcome such a problem, a new concept was introduced known as an inline function. When the function is encountered inside the main() method, it is expanded with its definition thus saving time.
We cannot provide the inlining to the functions in the following circumstances:
When do we require an inline function?
An inline function can be used in the following scenarios:
Advantages of inline function
Disadvantages of inline function
The following are the disadvantages of an inline function: