C Library Macros - va_arg()
va_arg The macro is a macro in the C standard library header used to successively obtain the value of each variadic argument in a variadic function. It is used after the va_start macro has initialized the va_list variable, to access the next argument in the variable argument list.
Declaration
The following is the declaration of the va_arg() macro.
type va_arg(va_list ap, type);
Parameters
va_list ap: ava_listvariable that has beenva_startinitialized by the macro and points to the current position in the variadic argument list.type: the type of the next argument to retrieve. It must be a type that can be unambiguously identified.
Return Value
Returns the next argument in the current variadic argument list, of type type.
Usage steps
- In a variadic function, use the
va_startmacro to initializeva_listvariable. - Use
va_argmacro to obtain each variadic argument in turn. - Use
va_endmacro cleanupva_listvariable.
Example
The following is an example of using va_arg a sample program for the macro that defines a variadic function to compute the sum of a variable number of arguments:
Example
#include
#include
// Variadic function that computes the sum of its arguments
int
sum
(
int
count
,
...
)
{
int
total
=
0
;
va_list args
;
// Initialize args to access the variadic arguments
va_start
(
args
,
count
)
;
// Retrieve each variadic argument in turn and add it to total
for
(
int
i
=
0
;
i
<
count
;
i
++
)
{
total
+=
va_arg
(
args
,
int
)
;
}
// Clean up args
va_end
(
args
)
;
return
total
;
}
int
main
(
)
{
printf
(
"Sum of 1, 2, 3: %d\n"
,
sum
(
3
,
1
,
2
,
3
)
)
;
// Output 6
printf
(
"Sum of 4, 5, 6, 7: %d\n"
,
sum
(
4
,
4
,
5
,
6
,
7
)
)
;
// Output: 22
return
0
;
}
Let's compile and run the above program, which will produce the following result:
Sum of 1, 2, 3: 6
Sum of 4, 5, 6, 7: 22
Parsing
va_list args;: declare ava_listvariable of typeargsto store information about the variadic argument list.va_start(args, count);: initializeargsto access the variadic arguments that begin aftercountthe last named argument.total += va_arg(args, int);: When usingva_argmacro retrieves the next variadic argument, assuming they are all of typeint, and adds it tototalvariable.va_end(args);: clean upargsto release resources and avoid undefined behavior.
Notes
va_argThe macro should be used afterva_startthe initialization macro, and beforeva_endthe cleanup macro.typeThe type argument must be an explicit type and should match the actual type of the variadic argument.- If calling
va_arggoes beyond the number of variadic arguments, the behavior is undefined. - Use
va_endClean upva_listvariable is necessary to avoid potential resource leaks or undefined behavior.
C Standard Library -