Syntax
#include <stdarg.h> var_type va_arg(va_list arg_ptr, var_type); void va_end(va_list arg_ptr); void va_start(va_list arg_ptr, variable_name);Description
va_arg, va_end, and va_start access the arguments to a function when it takes a fixed number of required arguments and a variable number of optional arguments. All three of these are macros. You declare required arguments as ordinary parameters to the function and access the arguments through the parameter names.
va_start initializes the arg_ptr pointer for subsequent calls to va_arg and va_end.
The argument variable_name is the identifier of the rightmost named parameter in the parameter list (preceding , ...). Use va_start before va_arg. Corresponding va_start and va_end macros must be in the same function.
va_arg retrieves a value of the given var_type from the location given by arg_ptr, and increases arg_ptr to point to the next argument in the list. va_arg can retrieve arguments from the list any number of times within the function. The var_type argument must be one of int, long, double, struct, union, or pointer, or a typedef of one of these types.
va_end is needed to indicate the end of parameter scanning.
va_arg returns the current argument. va_end and va_start do not return a value.
This example passes a variable number of arguments to a function, stores each argument in an array, and prints each argument.
#include <stdio.h>
#include <stdarg.h>
int vout(int max,...);
int main(void)
{
vout(3, "Sat", "Sun", "Mon");
printf("\n");
vout(5, "Mon", "Tues", "Wed", "Thurs", "Fri");
return 0;
}
int vout(int max,...)
{
va_list arg_ptr;
int args = 0;
char *days[7];
va_start(arg_ptr, max);
while (args < max) {
days[args] = va_arg(arg_ptr, char *);
printf("Day: %s \n", days[args++]);
}
va_end(arg_ptr);
/****************************************************************************
The output should be:
Day: Sat
Day: Sun
Day: Mon
Day: Mon
Day: Tues
Day: Wed
Day: Thurs
Day: Fri
****************************************************************************/
}
Related Information