inline functions lect 15
inline functions lect 15
Inline functions are commonly used when the function definitions are small, and the
functions are called several times in a program. Using inline functions saves time to transfer
the control of the program from the calling function to the definition of the called function.
To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.
// function code
Remember, inlining is only a request to the compiler, not a command. Compiler can ignore
the request for inlining. Compiler may not perform inlining in such circumstances like:-
3) If a function is recursive.
1
Notes By: Shirish Mohan Dubey (Asst. Prof. CS Dept.)
Btech – Cse III Sem Inline Functions
Following is an example, which makes use of inline function to return max of two numbers.
#include <iostream.h>
return(a+b);
Void main()
or cin>>x,y;
getch();
Output:-
Ans-5
Exampole:-
#include <iostream.h>
Void main () {
2
Notes By: Shirish Mohan Dubey (Asst. Prof. CS Dept.)
Btech – Cse III Sem Inline Functions
getch();
Output: -
Max (20,10): 20
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 pre-
processor 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.
In the inline function, we do not need to call a function, so it does not cause any
overhead.
It does not require any stack on which we can push or pop the variables as it does
not perform any function calling.
3
Notes By: Shirish Mohan Dubey (Asst. Prof. CS Dept.)