Functions that require variable lists are declared using the ellipsis (...) in the argument list, as described in Variable Argument Lists. To access arguments passed to functions using this method, use the types and macros described in the STDARG.H standard include file.
The following example shows how the va_start, va_arg, and va_end macros, along with the va_list type (declared in STDARG.H), work together:
#include <stdio.h>
#include <stdarg.h>
// Declaration, but not definition, of ShowVar.
int ShowVar( char *szTypes, ... );
void main()
{
ShowVar( "fcsi", 32.4f, 'a', "Test string", 4 );
}
// ShowVar takes a format string of the form
// "ifcs", where each character specifies the
// type of the argument in that position.
//
// i = int
// f = float
// c = char
// s = string (char *)
//
// Following the format specification is a list
// of n arguments, where n == strlen( szTypes ).
void ShowVar( char *szTypes, ... )
{
va_list vl;
int i;
// szTypes is the last argument specified; all
// others must be accessed using the variable-
// argument macros.
va_start( vl, szTypes );
// Step through the list.
for( i = 0; szTypes[i] != '\0'; ++i )
{
union Printable_t
{
int i;
float f;
char c;
char *s;
} Printable;
switch( szTypes[i] ) // Type to expect.
{
case 'i':
Printable.i = va_arg( vl, int );
printf( "%i\n", Printable.i );
break;
case 'f':
Printable.f = va_arg( vl, float );
printf( "%f\n", Printable.f );
break;
case 'c':
Printable.c = va_arg( vl, char );
printf( "%c\n", Printable.c );
break;
case 's':
Printable.s = va_arg( vl, char * );
printf( "%s\n", Printable.s );
break;
default:
break;
}
}
va_end( vl );
}
The preceding example illustrates these important concepts:
vl
.