Posted By:
3 Jul, 2013 12:56 pm PDT

Default values in parameters for a function

Can we have default values in parameters for a function?
Attachment:None


When declaring a function we can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead.

For example:

#include<iostream.h>

int multiply(int a,int b=2)

{

int mul;

mul=a*b;

return mul;

}

void main()

{

cout<< multiply(5);

cout<<endl;

cout<<multiply(4,3);

}

 

As we can see in the body of the program there are two calls to the function divide. In the first one:

 

multiply (5);

 

We have only specigied one argument, but the function multiply allows up to two. So the function divide has assumed the second parameter is 2 since that is what we specified to happen if this parameter was not passed. Therefore the result of the function call is 10 (5*2).

 

In the second call:

multiply (4,3);

There are two parameters, so the default value for b is ignored and b takes the value passed as argument, that is 3, making the result returned equal to 12 (4*3).

 

Attachment: default.cpp
Was it useful?  




Please login to reply to this problem.