Default arguments in C++

By: Babbar Ankit Viewed: 153215 times  Printer Friendly Format    


C++ provides the option of  providing default values to the arguments being passed to a function.

Consider the example

#include<iostream>
#include<iomanip>
using namespace std;

long int sum(int n,int diff=1,int first_term=1 )
{
long  sum=0;;
for(int i=0;i<n;i++)
{
cout<<setw(5)<<first_term+ diff*i;
   sum+=first_term+diff*i;
}
return sum;
}

int main()
{
cout<<endl<<\"Sum=\"<<setw(7)< <sum(10)<<endl;
//first term=1; diff=1,n=10
//sums the series 1,2,3,4,5………10

cout<<endl<<\"Sum=\"<<setw(7)< <sum(6,3,2)<<endl;
//first term=1; diff=2,n=10
//sums the series 2,5,8,11,14,17

cout<<endl<<\"Sum=\"<<setw(7)< <sum(10,2)<<endl;
//first term=1; diff=2,n=10
//sums the series 1,3,5………..19

return 1;
}

IMPORTANT

all the parameters with default values should lie to the right in the signature list i.e. the default arguments should be the trailing arguments—those at the end of the list.

when a function with default arguments is called, the first argument  in the call statement is assigned to the first argument in the definition, the 2nd to 2nd and so on.

This becomes more clear from the last call to sum() in the above example where value 10 is assigned to n and 2 is assigned to diff and not first_term.

 the default argument values appear in the prototype as well as definition.

You still may omit variable names in the prototypes.

The syntax then being

int xyz(int =2,char=5);

Authors Url: http://www.botskool.com/programming-tutorials



Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial