[Previous]
[Contents]
[Next]

va_arg()

get the next item in a list of variable arguments

Synopsis:

#include <stdarg.h>
type va_arg( va_list param, type );

Description:

va_arg() is a macro that can be used to obtain the next argument in a list of variable arguments. It must be used with the associated macros va_start() and va_end(). A sequence such as

void example( char *dst, ... )
{
    va_list curr_arg;
    int next_arg;

    va_start( curr_arg, dst );
    next_arg = va_arg( curr_arg, int );
    .
    .
    .

causes next_arg to be assigned the value of the next variable argument. The argument type (which is int in the example) is the type of the argument originally passed to the function.

The macro va_start() must be executed first, in order to initialize the variable curr_arg properly, and the macro va_end() should be executed after all arguments have been obtained.

The data item curr_arg is of type va_list that contains the information to permit successive acquisitions of the arguments.

Returns:

The value of the next variable argument, according to type passed as the second parameter.

Examples:

#include <stdio.h>
#include <stdarg.h>

void test_fn( const char *msg,
          const char *types,
          ... );

void main()
  {
    printf( "VA...TEST\n" );
    test_fn( "PARAMETERS: 1, \"abc\", 546",
         "isi", 1, "abc", 546 );
    test_fn( "PARAMETERS: \"def\", 789",
         "si", "def", 789 );
  }

static void test_fn(
  const char *msg,   /* message to be printed     */
  const char *types, /* parameter types (i,s)     */
  ... )          /* variable arguments     */
  {
    va_list argument;
    int   arg_int;
    char *arg_string;
    const char *types_ptr;

    types_ptr = types;
    printf( "\n%s -- %s\n", msg, types );
    va_start( argument, types );
    while( *types_ptr != \0 ) {
      if (*types_ptr == i) {
        arg_int = va_arg( argument, int );
        printf( "integer: %d\n", arg_int );
      } else if (*types_ptr == s) {
        arg_string = va_arg( argument, char * );
        printf( "string:  %s\n", arg_string );
      }
      ++types_ptr;
    }
    va_end( argument );
  }

produces the output:

VA...TEST

PARAMETERS: 1, "abc", 546 -- isi
integer: 1
string:  abc
integer: 546

PARAMETERS: "def", 789 -- si
string:  def
integer: 789

Classification:

ANSI

Safety:
Interrupt handler No
Signal handler Yes
Thread Yes

Caveats:

va_arg() is a macro.

See also:

va_end(), va_start(), vfprintf(), vprintf(), vsprintf()


[Previous]
[Contents]
[Next]