# va_arg Macro

Gets the next argument in a variable argument list represented by a va_list object.

Include

<stdarg.h>

Prototype

type va_arg(va_list ap, type)

Arguments

 ap pointer to list of arguments type type of argument to be retrieved

Return Value

Returns the next argument in the argument list represented by ap with the type specified as the second argument.

Remarks

The ap object must have been initialized by calls to either va_start or va_copy before va_arg can be used. If there is no next argument available or it is not of the type requested, the behavior is undefined.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

void tprint(const char *fmt, ...)
{
va_list ap;

va_start(ap, fmt);
while (*fmt)
{
switch (*fmt)
{
case '%':
fmt++;
if (*fmt == 'd')
{
int d = va_arg(ap, int);
printf("<%d> is an integer\n",d);
}
else if (*fmt == 's')
{
char *s = va_arg(ap, char*);
printf("<%s> is a string\n", s);
}
else
{
printf("%%%c is an unknown format\n",
*fmt);
}
fmt++;
break;
default:
printf("%c is unknown\n", *fmt);
fmt++;
break;
}
}
va_end(ap);
}
int main(void)
{
tprint("%d%s.%c", 83, "This is text.", 'a');
}

Example Output

<83> is an integer
<This is text.> is a string
. is unknown
%c is an unknown format