Get the next item in a list of variable arguments
#include <stdarg.h> type va_arg( va_list param, type );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
You can use the va_arg() macro to get the next argument in a list of variable arguments.
You must use va_arg() with the associated macros va_copy(), 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.
You must execute the macro va_start() first, in order to initialize the variable curr_arg properly, and execute the macro va_end() after getting all the arguments.
The data item curr_arg is of type va_list that contains the information to permit successive acquisitions of the arguments.
The following functions use a varargs list:
The value of the next variable argument, according to type passed as the second parameter.
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> static void test_fn( const char *msg, const char *types, ... ); int main( void ) { printf( "VA...TEST\n" ); test_fn( "PARAMETERS: 1, \"abc\", 546", "isi", 1, "abc", 546 ); test_fn( "PARAMETERS: \"def\", 789", "si", "def", 789 ); return EXIT_SUCCESS; } 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
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | Yes |
Signal handler | Yes |
Thread | Yes |
va_arg() is a macro.