Variable length argument lists
This program demonstrates how to declare and use functions in which the number and type of arguments passed to it are not known to the function itself.
Programming Issues
Functions which can take a variable number of arguments must be declared:
(type) func( (type) arg, ... );
At least one of the arguments must be known (i.e. int func(...)
is
illegal), and must all be placed before the ellipsis (the "...").
A variable of type va_list
must be declared.
Accessing the arguments involves three main steps:
- Calling
va_start(va_list argptr, last_arg)
whereargptr
is the variable declared earlier, andlast_arg
is the name of the last known argument before the ellipsis. - Looping through the number of arguments, retrieving each one in
turn with
va_arg(va_list argptr, type)
wheretype
is the type of the argument, such asint
orchar *
. There are a number of ways to determine the number and type of arguments. In the functionsum()
, each argument is always of typeint
, and the argumentnArgs
supplies the number of arguments to the function. In the functionPrintArgs()
, the length of the format string passed to it gives the number of arguments, and the type of each argument is determined by examining the characters in the string. This is similar to howprintf()
works. - Calling
va_end(va_list argptr)
to clean up nicely. This step must be carried out.
Usage
Execute the program as normal.