Default arguments in C++
By: Babbar Ankit
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+
sum+=first_term+diff*i;
}
return sum;
}
int main()
{
cout<<endl<<\"Sum=\"<<setw(7)<
//first term=1; diff=1,n=10
//sums the series 1,2,3,4,5………10
cout<<endl<<\"Sum=\"<<setw(7)<
//first term=1; diff=2,n=10
//sums the series 2,5,8,11,14,17
cout<<endl<<\"Sum=\"<<setw(7)<
//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
Archived Comments
1. dear sir, plz answer my following questions:
Q1- Why should all normal arguments prec
View Tutorial By: hawa at 2012-01-29 08:29:39
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++