Functions with Default Values in the Signature


There are functions for which an argument is needed only infrequently or that the same value is frequently used for the argument. For these and other cases DEFAULT VALUES IN THE SIGNATURE of a function may be the best solution.

In order to use this type of function, the declaration must have its signature arranged into two types of arguments: MANDATORY and DEFAULT arguments. The mandatory must precede the default in a left to right manner. Values must be passed to all mandatory arguments and values may be passed to the default arguments. If a value is passed to a default argument, then the value passed overrides the default one. If a default argument is overridden, then all of the default arguments to the left of it must be overridden as well. For example, it would not be possible to override the 1st and the 3rd default argument without also overriding the 2nd. (Note: The default values are part of the declaration. Therefore if the prototype is the declaration, then the default values do not appear in the function's definition.)

Default arguments are created in the signature to the right of the mandatory arguments by

  • indicating the data type of the argument

  • naming the variable immediately to the right of the data type

  • listing the assignment operator (=) after the default variable

  • listing the default value to be passed to the variable after the assignment operator.

For example, suppose that the function: f( ) had the following prototype:

image from book

 int f(int a, int b, int c=6, int d=10); 

image from book

then some possible calls for f() are:

image from book

 f(5,6);      //   both defaults used f(5,6,7);    //  1st default is overridden f(5,6,7,8);  //  both defaults are overridden 

image from book

In this example the default arguments only appear in the declaration but not in the definition or the call. See DEFLTVLU.CPP

Functions with default values can increase a programmer's productivity. There are times in which it may be necessary to add arguments to a function that has been around a long time. However if an argument is added, all code where that function was called previously would have to be changed. This could open the program to many bugs. Redefining the function with default values can reduce this problem. For another example, see DEFLTMSG.CPP




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net