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:
va_start. The argument pointer when initialized points to the first optional argument.
va_arg. The first call to
va_arggives 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.
(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
See Argument Macros, for the full definitions of
Steps 1 and 3 must be performed in the function that accepts the
optional arguments. However, you can pass the
as an argument to another function and perform all or part of step 2
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