Setting default parameters in function prototype
The default parameters in function becomes active when given parameter value is not passed. Here we learn this setting at the level of function prototype.
Learning Objectives
- Understanding setting of default parameter values while definition the function prototype.
- Practical application of working of default parameter concept.
Source Code
|
|
Alternate (?) : |
Run Output
Code Understanding
void repeat(char = ‘#’,int = 20);
This is a prototype of functions with default parameters. The default parameter setting should begin from last parameter on the right and continue till the first parameter. If any default parameter is set and then all default values for parameters towards its right must also be set. In this case we have set both the default parameters.
char c=’@’;Β int rc=10;
This are values set to be passed as actual parameters from the calling functions if desired.
repeat(c);cout<<endl;
Here we are calling the function with just first parameter and second parameter has been skipped. In this case second parameter value will be set to default param. In this case default param for repeat count is 20, so the character based on parameter 1 which is @ character shall be printed 20 times.
repeat(c,rc);cout<<endl;
In this case both parameters have been passed so the default parameters shall not be used and the character @ will be printed 10 times.
repeat();
In this case both parameters have been omitted so all the default parameters shall be used, so # will be printed 20 times.
void repeat(char a,int rc)
This function definition header where two parameters are passed and no output is returned.
for(int i=0;i<rc;++i) cout<<a;
Here the repetition is done on the basis of char as passed or as set by the default value up to repetition count as passed in argument or as set as default value.
Notes
- Default parameters can be set at the function prototype level or at the level of function definitions if they are provided before the calling function such as the main() function.
Common Errors
- Most common error is incorrect calling. For eg. in above case
repeat(,10) will not be valid due to missed parameter from the beginning. Parameter can be missed from the right side on wards if the default parameter is set for them.
repeat(10,’#’) will not be valid due to in incorrect order of parameters.
Suggested Filename(s): fn-def-param-p.cpp, defparp.cpp
Created: 5-Jan-2018 20:13 | Updated: 15-Sep-2018 14:07|
