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:

  1. Calling va_start(va_list argptr, last_arg) where argptr is the variable declared earlier, and last_arg is the name of the last known argument before the ellipsis.
  2. Looping through the number of arguments, retrieving each one in turn with va_arg(va_list argptr, type) where type is the type of the argument, such as int or char *. There are a number of ways to determine the number and type of arguments. In the function sum(), each argument is always of type int, and the argument nArgs supplies the number of arguments to the function. In the function PrintArgs(), 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 how printf() works.
  3. Calling va_end(va_list argptr) to clean up nicely. This step must be carried out.

Usage

Execute the program as normal.

Source and Downloads