C++ allows a function to assign a parameter the default value in case no argument for that parameter is specified in the function call.
Default arguments also called an optional parameter (or) default
parameter. Default argument is a function parameter that has a default value
provided to it. If the user does not supply a value for this parameter, the
default value will be used. If the user does supply a value for the default
parameter, the user supplied value is used instead of the default value.
#include<iostream.h>
#include<conio.h>
void display(char ch='a',int i=10,float f=2.56);
void main()
{
clrscr();
display();
display('s');
display('d',20);
display('n',30,4.96);
getch();
}
void display(char ch,int i,float f)
{
cout<<ch<<" "<<i<<" "<<f<<"\n"<<"\n";
}
output:
Note:
Once the default value
is used for an argument, all the sub sequent arguments must have default
values.
int sum( int a, int b=1, int c=6, int d);
It is invalid because c
has default value, but d after doesn’t have default value (all
default parameters must be the rightmost parameters)
No comments:
Post a Comment