Inline functions

Raju Pal

Inline function are used to reduced the calling overhead introduced by functions in C++.

  • A function is either declared, defined or called. When the function was called, the control jump to memory address contained in function name.
  • Yes, function names contains the addresses similar to variable name.
  • More function calling in the program increases the overhead which results in poor performance.
  • Hence, it is always desirable to make function small and declared inline.

To make a function inline, inline keyword has to be appended with function name. For example,

inline void add(int a, int b) { //Give body here }

The above defined function does not need to be jumped to the another memory address in order to evaluate the function, instead, the function would be copies in current memory space and evaluated in current memory space. This reduces the calling overhead of functions.

Example:

#include<iostream>
class Study 
{ 
	public: 
	inline int add(int x,int y) { return(x+y); } 
	inline float square(float i) { return(i*i); } 
}; 
int main() 
{ 
	Study obj; 
	int a,b; 
	cout<<"Enter two values:"; cin>>a>>b; 
	cout<<"\n Sum of two values is:"<<obj.add(a,b); 
	cout<<"\n\n Square value of a and b is :"<<obj.square(a)<<"\t"<<obj.square(b); 
} 

Output: 
Enter two values: 5 7 
Sum of two values is: 12 
Square value of a and b is: 25 and 49

What do you think about the article?

This site uses Akismet to reduce spam. Learn how your comment data is processed.