Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Function with Default Arguments

Default argument is a concept of C++ in which a function assigns default values for some or all of the
formal arguments which does not have a matching argument in the function call. And those default values
are known as Default Arguments.

This allows a programmer to call a function without assigning all its arguments. If no value is passed for
any of the formal arguments when the function is called, the default value specified in the function
prototype is passed to the corresponding formal argument. If all the arguments are passed when the
function is called, then the default value is ignored.

#include<iostream>
using namespace std;
void add(int,int,int=5);
int main()
{
add(10,20,30);
add(10,20);

return 0;
}

void add(int a,int b,int c)


{
int sum;
sum=a+b+c;
cout<<endl<<sum;
}
Feature of Default Arguments

1. Default values can be assigned to more than one argument.

Eg:
void add(int a,int b,int c=5,int d=6);

2. Default values can also be assigned without using argument names.

Eg:
void add(int,int,int=5,int=6);

3. Default values to the arguments must be assigned starting from the right most argument i.e before
assigning the default value to an argument, all the arguments to its right must be given default
value. In other sense, default value to a particular argument cannot be provided in the middle of
the argument list.

Eg:
void add(int a,int b,int c=5,int d); //Error
void add(int a,int b,int c=5,int d=10); //correct

4. The default values are assigned when the function is declared i.e in the function prototype.

You might also like