C++ allows us to call a function without specifying all its arguments.
Default values are specified when function is declared.
Compiler looks at the prototype to see how many arguments, a function uses and alerts the program for possible default values.
Declaration of function with default values
float amt(float prin_amt, int period, float rate = 0.12)
A function call
float value = amt(500,7);
Passes value 500 to prin_amt and 7 to perod and then function uses 0.12 for rate.
A function call
float value = amt(500,7,0.15);
Passes explicit value of 0.15 to rate.
Only the trailing argument can have default values i.e. We can add default values from right to left. We can not provide default values in the middle of argument list.
#include<conio.h>
#include<iostream.h>
int volume(int len = 1, int wdt = 1, int hgt = 1);
void main( )
{
clrscr( )
{
cout<<"\n\n\tDefault box volume is--->"<<volume( );
cout<<"\n\n\tThe Volume with length 10 is--->"<<volume(10);
cout<<"\n\n\tThe Volume of the length 10 and width 10 is--->"<<volume(10,10);
cout<<"\n\n\tThe Volume with length 10, width 10 and height 10 is--->"<<volume(10,10,10);
getch( );
}
int volume(int len, int wdt, int hgt)
{
return(len*wdt*hgt);
}
Output:-
Default box volume is--->1
The Volume with length 10 is--->10
The Volume of the length 10 and width 10 is--->100
The Volume with length 10, width 10 and height 10 is--->1000
Default values are specified when function is declared.
Compiler looks at the prototype to see how many arguments, a function uses and alerts the program for possible default values.
Declaration of function with default values
float amt(float prin_amt, int period, float rate = 0.12)
A function call
float value = amt(500,7);
Passes value 500 to prin_amt and 7 to perod and then function uses 0.12 for rate.
A function call
float value = amt(500,7,0.15);
Passes explicit value of 0.15 to rate.
Only the trailing argument can have default values i.e. We can add default values from right to left. We can not provide default values in the middle of argument list.
#include<conio.h>
#include<iostream.h>
int volume(int len = 1, int wdt = 1, int hgt = 1);
void main( )
{
clrscr( )
{
cout<<"\n\n\tDefault box volume is--->"<<volume( );
cout<<"\n\n\tThe Volume with length 10 is--->"<<volume(10);
cout<<"\n\n\tThe Volume of the length 10 and width 10 is--->"<<volume(10,10);
cout<<"\n\n\tThe Volume with length 10, width 10 and height 10 is--->"<<volume(10,10,10);
getch( );
}
int volume(int len, int wdt, int hgt)
{
return(len*wdt*hgt);
}
Output:-
Default box volume is--->1
The Volume with length 10 is--->10
The Volume of the length 10 and width 10 is--->100
The Volume with length 10, width 10 and height 10 is--->1000
0 Comments:
Post a Comment