C Language: va_arg function
(Fetch Argument from Variable Argument List)
In the C Programming Language, the va_arg function fetches an argument in a variable argument list.
The va_arg function updates ap so that the next call to the va_arg function fetches the next argument. You must call the va_start function to initialize ap before using the va_arg function.
Syntax
The syntax for the va_arg function in the C Language is:
type va_arg(va_list ap, type);
Parameters or Arguments
- ap
- A variable argument list.
- type
- The type of the argument.
Returns
The va_arg function returns the value of the argument.
Required Header
In the C Language, the required header for the va_arg function is:
#include <stdarg.h>
Applies To
In the C Language, the va_arg function can be used in the following versions:
- ANSI/ISO 9899-1990
va_arg Example
/* Example using va_arg by TechOnTheNet.com */ #include <stdio.h> #include <stdarg.h> int add(int n, ...) { /* Define temporary variables */ va_list list; int total; /* Initialize total */ total = 0; /* Set where the variable length part of the argument list ends */ va_start(list, n); /* Loop through each argument adding the int values */ for (int i=0; i < n; i++) total = total + va_arg(list, int); /* Clean up */ va_end(list); /* Return the calculated total */ return total; } int main(int argc, const char * argv[]) { /* Define temporary variables */ int value1, value2, value3; int result; value1 = 1; value2 = 2; value3 = 3; /* Call the add function */ result = add(4, value1, value2, value3); /* Display the results of the additon */ printf("The sum of %d, %d and %d is %d\n", value1, value2, value3, result); return 0; }
When compiled and run, this application will output:
The sum of 1, 2 and 3 is 6
See Also
Other C functions that are noteworthy when dealing with the va_arg function:
Advertisements