C Library Macro - va_arg()
C Standard Library - <stdarg.h>
Description
The C library macro type vaarg(valist ap, type) retrieves the next argument in the function's argument list of type type. It cannot determine whether the retrieved argument is the last argument passed to the function.
Declaration
Below is the declaration for the va_arg() macro.
type va_arg(va_list ap, type)
Parameters
ap -- This is an object of type va_list that holds information about additional arguments and their retrieval state. This object should be initialized by calling va_start before the first call to va_arg.
type -- This is a type name. The type name is used as the type of the expression that expands from this macro.
Return Value
The macro returns the next additional argument, which is an expression of the specified type.
Example
The following example demonstrates the usage of the va_arg() macro.
#include <stdarg.h>
#include <stdio.h>
int sum(int, ...);
int main()
{
printf("Sum of 15 and 56 = %d\n", sum(2, 15, 56) );
return 0;
}
int sum(int num_args, ...)
{
int val = 0;
va_list ap;
int i;
va_start(ap, num_args);
for(i = 0; i < num_args; i++)
{
val += va_arg(ap, int);
}
va_end(ap);
return val;
}
Let's compile and run the above program, which will produce the following result:
Sum of 15 and 56 = 71