VARIABLE NUMBER OF ARGUMENTS
Examine the program named VARARGS.CPP for an illustration of the use of a variable number of arguments in a function call.
// Declare a function with one required parameter
void display_var(int number, ...);
int index = 5;
int one = 1, two = 2;
display_var(3, index, index + two, index + one);
display_var(two, 7, 3);
void display_var(int number, ...)
va_start(param_pt,number); // Call the setup macro
cout << "The parameters are ";
for (int index = 0 ; index < number ; index++)
cout << va_arg(param_pt,int) << " "; // Extract a parameter
cout << "n";
va_end(param_pt); // Closing macro
// Result of Execution
// The parameters are 5
// The parameters are 5 7 6
// The parameters are 7 3
We have gone to a lot of trouble to get the compiler to help us by carefully checking how many parameters we use in the function calls and checking the types of the parameters. On rare occasion, we may wish to write a function that uses a variable number of parameters. The printf() function is a good example of this. ANSI-C has a series of three macros available in the “stdarg.h” header file to allow the use of a variable number of arguments. These are available for use with C++ also, but we need a way to eliminate the strong type checking that is done with all C++ functions. The three dots illustrated in line 6 will do this for us. This prototype says that a single argument of type int is required as the first parameter, then no further type checking will be done by the compiler.
You will note that the main program consists of three calls to the function, each with a different number of parameters, and the system does not balk at the differences in the function calls. Infact, you could put as many different types as you desire in the calls. As long as the first one is an int type variable, the system will do its best to compile and run it for you. Of course the compiler is ignoring all type checking beyond the first parameter so it is up to you to make sure you use the correct parameter types in this call.
In this case the first parameter gives the system the number of additional parameters to look for and handle. In this simple program, we simply display the numbers on the monitor to illustrate that they really did get handled properly.
Of course, you realize that using a variable number of arguments in a function call can lead to very obscure code and should be used very little in a production program, but the capability exists if you need it. Be sure to compile and execute this program.