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.

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.