inline functions in c++


In C++ inline Function

The benefits of inline functions are as follows :

• Better than a macro.
• Function call overheads are eliminated.
• Program becomes more readable.
• Program executes more efficiently.
• The speed benefits of inline functions decreases as function grows in size.
• Therefore functions are made inline when they are small enough to be defined in one or two lines.

Following situations where inline may not works

• For functions returning values, if a loop, a switch, or a goto exists.
• For functions not returning values, if a return statement exists.• If function contains static variables.
• If inline functions are recursive.

 

The function designed to speed up program execution.
An inline function is expanded (i.e. the function code is replaced when a call to the inline function is made) in the line where it is invoked.
You are familiar with the fact that in case of normal functions, the compiler have to jump to another location for the execution of the function and then the control is returned back to the instruction immediately after the function call statement.
So execution time taken is more in case of normal functions.
There is a memory penalty in the case of an inline function.

Syntax

inline function header
{
function body
}

Example

inline int cube (int a)
{
return (a * a * a);
}
inline void min (int x, int y)
{
cout<< (x < y)  ? x : y ;
}
This function can be called as c = cube(5);
Its  Request to compiler,  All inline functions must be defined before they are called.

Example Program of inline function

 

output of inline Function program

35
15

(Visited 23 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image