Default Parameters
In function prototyping we do specify the number of parameters, types of the parameters and the order in which the types parameter passed in and the return type. It is not required to specify the argument names in the function proto-typing.
Consider the declaration below:
int add_numbers(int x, int y=0, int z = 0);
Here, we specified the argument names along with the argument types. Also note that we need to specify the default value for the second and third arguments. And in our above example it is 0 for third and second Parameters.
One more point, the default parameters should be specified from Right to the Left. That is, it is not possible to specify the default parameter when the parameter next to it is not a default parameter. Consider the below statement now:
int add_numbers(int x, int y=0, int z);
This is wrong. Because at runtime it not possible to skip second parameter and pass value to the third one. Have look at the calling code below:
add_numbers(12, 14);
The value 14 always goes to argument y as the order matters. I can say like this also, how does the compiler knows the value 14 is for Y or Z. So, the rule of thumb is, second parameter value is for second argument y.
Below is the Example for Default parameters:
#include "stdafx.h"
#include <conio.h>
int
add_numbers(int x, int y=0, int z = 0);
int
add_numbers(int x, int y, int z)
{
return x+y+z;
}
int _tmain(int argc,
_TCHAR* argv[])
{
int x = 15, y = 15, z = 12;
printf("Added
Result : %d\n", add_numbers(x));
printf("Added
Result : %d\n", add_numbers(x, y ));
printf("Added
Result : %d\n", add_numbers(x, y, z ));
getch();
return 0;
}

Comments
Join the conversation! Your thoughts help the community grow.