Sunday, February 13, 2011

Default arguments:


Default arguments:
C++ allows to use default argument if function call doesn’t pass its all arguments. When a function is called without specifying all its arguments, the c++ function assigns a default value to the parameter which does not have a matching argument in the function call. The default values are specified in function prototypes.
An example:
#include<iostream.h>
#include<conio.h>
float interest(float,float,float=20);
void main()
{
clrscr();
float interst_result, interst_result_default;
interst_result=interest(1000,2,30);
interst_result_default=interest(1000,2);
cout<<"Interest with rate 30% is "<<interst_result<<endl<<"Intrest with default rate 20%                
                            "<<interst_result_default;
getch();
}

float interest(float p, float t, float r)
{
return((p*t*r)/100);
}

Output:
Interest with rate 30% is 600
Intrest with default rate 20% 400

                   In this example, default value for parameter rate is specified in the prototype of interst() function. When this function is called by specifying all arguments like interest(1000,2,30) (i.e. all three arguments p,t and r), the default value is not used. The supplied values are used to calculate the interest. But when the function is called by specifying only two arguments like interest(1000,2), the default value for rate is used to calculate the interest.

  While specifying default arguments, default values can be specified only for trailing arguments. The default values are added from right to left in the function prototype. The default value can not be provided to a particular argument in the middle of an argument list. This is illustrated by following some function prototypes.

float interest(float p, float t, float r=20);       //valid
float interest(float p, float t =2, float r);        //invalid
float interest(float p, float t=2, float r=20);   //valid
float interest(float p=1000, float t, float r);  //invalid

No comments:

Post a Comment