Next: , Previous: Variadic Prototypes, Up: How Variadic


A.2.2.2 Receiving the Argument Values

Ordinary fixed arguments have individual names, and you can use these names to access their values. But optional arguments have no names—nothing but `...'. How can you access them?

The only way to access them is sequentially, in the order they were written, and you must use special macros from stdarg.h in the following three step process:

  1. You initialize an argument pointer variable of type va_list using va_start. The argument pointer when initialized points to the first optional argument.
  2. You access the optional arguments by successive calls to va_arg. The first call to va_arg gives you the first optional argument, the next call gives you the second, and so on.

    You can stop at any time if you wish to ignore any remaining optional arguments. It is perfectly all right for a function to access fewer arguments than were supplied in the call, but you will get garbage values if you try to access too many arguments.

  3. You indicate that you are finished with the argument pointer variable by calling va_end.

    (In practice, with most C compilers, calling va_end does nothing. This is always true in the GNU C compiler. But you might as well call va_end just in case your program is someday compiled with a peculiar compiler.)

See Argument Macros, for the full definitions of va_start, va_arg and va_end.

Steps 1 and 3 must be performed in the function that accepts the optional arguments. However, you can pass the va_list variable as an argument to another function and perform all or part of step 2 there.

You can perform the entire sequence of three steps multiple times within a single function invocation. If you want to ignore the optional arguments, you can do these steps zero times.

You can have more than one argument pointer variable if you like. You can initialize each variable with va_start when you wish, and then you can fetch arguments with each argument pointer as you wish. Each argument pointer variable will sequence through the same set of argument values, but at its own pace.

Portability note: With some compilers, once you pass an argument pointer value to a subroutine, you must not keep using the same argument pointer value after that subroutine returns. For full portability, you should just pass it to va_end. This is actually an ISO C requirement, but most ANSI C compilers work happily regardless.