Setting default parameters in function definition – CSKC
Sign In

Search

Code Learning #CPP#2250    siteicon   siteicon  

Setting default parameters in function definition

The default parameters in function becomes active when given parameter value is not passed. Here we learn this setting at the level of function definition.

Learning Objectives

  • Understanding setting of default parameter values while giving them in the function definition.
  • Learning to use the correct order of setting the default parameters.

Source Code

TC++ #2250

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Alternate (?) :

Code Understanding

void repeat(char a=’#’,int rc=20)
{

This is header of  the function definition with default parameters. It can be given this way only when the definition is given above the calling function which is the main() function in this example. 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.

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.
}

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.

 

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



Share

Created: 5-Jan-2018 20:42 | Updated: 15-Sep-2018 14:08|