va_arg
Obtains the next argument in a list of variable arguments (macro)
#include <stdarg.h>
type va_arg (
va_list param,
type);
va_arg returns the value of the next variable argument, according to type passed as the second parameter.
The macro va_arg 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:
va_list curr_arg;
type next_arg;
next_arg = va_arg (curr_arg, type);
causes next_arg to be assigned the value of the next variable argument. The type is the type of the argument originally passed.
The macro va_start must be executed first in order to properly initialize the variable next_arg and the macro va_end should be executed after all arguments have been obtained.
The data item curr_arg is of type va_list which contains the information to permit successive acquisitions of the arguments.
#include <stdarg.h>
void test_fn (const char *msg, const char *types, ...);
int 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;
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 following:
PARAMETERS: 1, "abc", 546 integer: 1 string: abc integer: 546 PARAMETERS: "def", 789 string: def integer: 789