Você está na página 1de 11

Inline functions

An inline function is a function that is expanded in line when it is invoked. That is, the compiler replaces the function call with function definition.

Why do we use inline functions


Every time a function is called it takes a lot of extra time in executing series of instructions for tasks such as jumping to function, saving registers, returning to calling function. When function is small, huge execution time is spent in such overheads To eliminate the cost of calling small functions, INLINE functions are used.

SYNTAX
Inline function-header { Function body; }

Example
inline float square(float x) { return x*x; } void main() { float a,y; a=square(y); } During compilation this code is treated as:

void main() { float a,y; a=y*y; }

While making inline functions all we need to do is to prefix the keyword inline to function definition.

All inline functions must be defined before they are called. Usually, the functions are made inline when they are small enough to be defined in 1 or 2 lines.

Situations where inline expansion may not work:


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

Illustration
#include<iostream.h> #include<conio.h> inline int mult(int x,int y) { return(x*y); } inline int sum(int a,int b) { return(a+b); } int main() { int p,q; cout<<mult(p,q); cout<<sum(p,q); return 0; }

Default arguments
To call a function without specifying its arguments. In such cases, function assigns a default value to the parameter which does not have a matching arguments in the function call. Default values are specified when function is declared.

Example of function declaration with default values


float amount(float principal,int time,int rate=2); // default value of 2 is assigned to rate Amount(5000,5); // this function call passes value of 5000 to principal and 5 to time and function uses default value of 2 for rate. Amount(5000,5,1); //no missing argument,it passes an explicit value of 1 to rate

NOTE: only trailing arguments can have default values. We must add default values from right to left. We can not provide default value to an argument in the middle of argument list. int sum(int i, int j=5, int k=9); //Right int sum(int i=5, int j); //wrong int sum(int i=0, int j; int k=5); //wrong

Advantages
We can use default arguments to add new parameters to existing functions. Default arguments can be used to combine similar functions into one.

Você também pode gostar