va_arg() – va_end() – va_start() — Access Function Arguments

Format

#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);

Language Level: ANSI

Threadsafe: Yes.

Description

The va_arg(), va_end(), and va_start() functions access the arguments to a function when it takes a fixed number of required arguments and a variable number of optional arguments. 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.

The va_arg() function 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. The va_arg() function can retrieve arguments from the list any number of times within the function. The var_type argument must be one of int, long, decimal, double, struct, union, or pointer, or a typedef of one of these types.

The va_end() function is needed to indicate the end of parameter scanning.

Because it is not always possible for the called routine to determine how many arguments there are, the calling routine should communicate the number of arguments to the called routine. To determine the number of arguments, a routine can use a null pointer to signal the end of the list or pass the count of the optional arguments as one of the required arguments. The printf() function, for instance, can tell how many arguments there are through the format-string argument.

Return Value

The va_arg() function returns the current argument. The va_end and va_start() functions do not return a value.

Example that uses va_arg()va_end()va_start()

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");
}
 
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);
}
 
/******************  Output should be similar to:  ****************
 
Day:  Sat
Day:  Sun
Day:  Mon
 
Day:  Mon
Day:  Tues
Day:  Wed
Day:  Thurs
Day:  Fri
*/

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]