on Leave a Comment

C++ Default Arguments

C++ provides us the facility to call function without specifying all its arguments. Compiler assigns default value to argument, that is not specified during function calling. Programmer must specify that default values during function declaration. Compiler sees the function prototype to check which argument can take default value.

Program to understand default arguments in C++

#include<iostream>
using namespace std;
void mul(int, int, int=1, int=1);
int main()
{
    mul(1,2);
    mul(1,2,3);
    mul(1,2,3,4);
    return 0;
}
void mul(int p,int q,int r,int s)
{
    cout<<endl;
    cout<<"Product is "<<p*q*r*s;
}
OUTPUT
Product is 2
Product is 6
Product is 24

We can also write void mul(int p, int q, int r=1, int s=1); instead of void mul(int, int, int=1, int=1);.

This program can calculate multiplication of 2 number, three numbers and 4 numbers. We specify default value (1) to arguments r and s. In the statement mul(1,2); we do not specify values of r and s. At this moment compiler automatically assigns 1 to both r and s variables.

Important point about default arguments in C++

We must add default values from right to left. We cannot specify default values at the middle of arguments list.

Here, following statements would work

void mul(int p, int q, int r, int s=1);
void mul(int p, int q, int r=1, int s=1);
void mul(int p, int q=1, int r=1, int s=1);
void mul(int p=1, int q, int r=1, int s=1);

Here, following statement would not work

void mul(int p=1, int q, int r, int s);
void mul(int p, int q=1, int r, int s);
void mul(int p, int q, int r=1, int s);

0 comments:

Post a Comment