Function-Default-Argument in c++ .

In this session i have discussed function default argument in C++ .


The function default argument is a new feature in C++ . The C++ allow us to call a function without specifying its all arguments . In such cases , The function assign a default value to the parameter which does not have matching argument in the calling function . Default values are specified when the function is declared .


Function Default Argument Syntax

    int sum(int x,int y=10);
    

In the above function when you call the function only supply the one value . The second value is default argument .


Example : Write a program that demonstrate the function default argument .

  #include<iostream>
  using namespace std; 
  int sum(int x,int y=10)
  {
        return(x+y);
  }
  int main()
  {  
       int x=10;
       cout<<"\nSum :  "<<sum(x);
       return 0;
  }
  
  
  OUTPUT : Sum : 20
           
    


Example : Write a program that demonstrate the function default argument .

  #include<iostream>
  using namespace std; 
  float simple_interest(int p,int t,float r=0.10f)
  {
        return(p*r*t);
  }
  int main()
  {  
       int p=100;
       int t=2;
       cout<<"\nSimple Interest :  "<<simple_interest(p,t);
       return 0;
  }
  
  
  OUTPUT : Simple Interest : 20
           
    


Welcome to AndroidATPoint.

back image                     next image