Inline Function in C++ with Example
Inline Function:
An inline function is a function that is expanded in line when it is invoked, the compiler replaces the function call with the corresponding function code. It has the following syntax:
inline function-header { functions of the body }
Example:
inline float square (float a) { return(a*a); }
Example:
#include<iostream.h> #include<conio.h> using namespace std; inline float add(float a, float b) { return(a+b); } inline double sub(double c, double d) { return(c-d); } int main() { float x=15.7567; float y=12.56; cout<<add(x,y)<<endl; cout<<sub(x,y)<<endl; return 0; }
Default Arguments:
C++ allows us to call a function without specifying all its arguments. The function assigns default values to the parameters which do not have a matching argument in the function call. Default Arguments in C++ are checked for data type at the time of declaration and evaluated at the time of the call. In this case, only Default Arguments in C++ can have default values and we must add defaults from right to left, we can’t provide a default value to a particular argument in the middle of an argument list.
Example:
#include<iostream.h> #include<conio.h> using namespace std; int main() { float amount; float value(float p, int n, float r=0.15); void printline(char ch='*', int l=50); printline(); amount=value(75000.500, 6); cout<<"Final value="<<amount<<endl; amount=value(12000.750, 7,0.50); cout<<"Final value="<<amount<<endl; printline('*'); getch(); return 0; } float value(float p, int n, float r) { int y=1; float sum=p; while(y<=n) { sum=sum*(1+r); y=y+1; } return(sum); } void printline(char ch, int l) { for(int i=1;i<=l;i++) printf("%c",ch); printf("\n"); }