Inline Function in C++

Advertisements

C++ Inline Function

One of the advantage of using function is to save memory space by making common block for the code we need to execute many times. When compiler invoke / call a function, it takes extra time to execute such as jumping to the function definition, saving registers, passing value to argument and returning value to calling function. This extra time can be avoidable for large functions but for small functions we use inline function to save extra time.

When we make an inline function, compiler will replace all the calling statements with the function definition at run-time.

Example of inline function


	#include<iostream.h>

	inline int Add(int x,int y)
	{

		return x+y;
	}

	void main()
	{

		cout<<"\n\tThe Sum is : " << Add(10,20);
		cout<<"\n\tThe Sum is : " << Add(45,83);
		cout<<"\n\tThe Sum is : " << Add(27,48);

	}

	Output :

	The Sum is : 30
	The Sum is : 98
	The Sum is : 75

				

Example of inline function at run-time


	#include<iostream.h>

	inline int Add(int x,int y)
	{

		return x+y;
	}

	void main()
	{

		cout<<"\n\tThe Sum is : " << 10+20;    //no need to jump at inline function
		cout<<"\n\tThe Sum is : " << 45+83;    //no need to jump at inline function
		cout<<"\n\tThe Sum is : " << 27+48;    //no need to jump at inline function

	}

	Output :

	The Sum is : 30
	The Sum is : 98
	The Sum is : 75

				

Advertisement