A function can be prototyped in C++ by using default arguments. This means that if the invoking statement omits certain fields, predefined default values will be supplied by the function. Default argument definitions cannot be spread throughout a function’s prototype; they must be the last formal parameters defined. The following example program demonstrates how to define and use such a function:
// // defrag.cpp // C++ program demonstrates how to prototype functions // with default arguments. Default arguments must always // be the last formal parameters defined. // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
#include <iostream.h>
void fdefault_argument(char ccode=’Q’, int ivalue=0, double fvalue=0);
Notice that in this program, all three formal parameter types have been given default values. The function fdefault( ) checks the ccode value to switch on or off an appropriate message. The output from the program is straightforward:
ivalue = 2 fvalue = 12.34
Using default values only. ivalue = 0 fvalue = 0
Careful function prototyping, using default argument assignment, can be an important approach to avoiding unwanted side effects. This is one means of guaranteeing that dynamically allocated variables will not have garbage values if the user did not supply any. Another way to initialize dynamically allocated memory is with the function memset( ).