ILE C/C++ Run-Time Library Functions


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.

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 | Table of Contents | Index ]