The <cstdarg>
header is a wrapper for the C standard <stdarg.h>
header, which declares macros for accessing the arguments to a function that takes a variable number of arguments, that is, a function that is declared with an ellipsis as the last parameter. Example 13-8 shows how a function can use the <cstdarg>
macros.
Example 13-8: Finding the maximum value of any number of arguments.
#include <cstdarg> // Use a trivial wrapper class to ensure va_end is called. class varargs { public: ~varargs() { va_end(ap); } std::va_list& ap; }; template <typename T> T max(unsigned count, ...) { assert(count > 0); varargs va; va_start(va.ap, count); T result = va_arg(va.ap, T); // get first argument while (--count > 0) { T arg = va_arg(va.ap, T); // get successive arguments if (arg > result) result = arg; // remember the largest } return result; }
Get next argument
T va_arg(va_list ap, T)
The va_arg
macro fetches the next argument, which must be of type T
. The ap
parameter must have been initialized by calling va_start
.
End getting arguments
void va_end(va_list ap)
The va_end
macro finishes fetching arguments. You must call va_end
once for each call to va_start
.
Argument list
typedef ... va_list;
The va_list
type is an opaque type that refers to the function's arguments. Declare a local variable of type va_list
, and supply the variable to the va_start
, va_arg
, and va_end
macros.
Start getting arguments
void va_start(va_list& ap, lastNamedParm)
The va_start
macro initializes ap
and prepares to fetch function arguments with va_arg
. You must call va_end
to clean up and finalize ap
.