C programming stdarg.h Macro - type va_arg(va_list ap, type)
In C programming, the stdarg.h
header file provides a set of functions and macros for working with functions that take a variable number of arguments. One of the most important macros in this header file is va_arg()
, which retrieves the next argument from a va_list
object.
The va_arg()
macro takes two arguments:
type va_arg(va_list ap, type);
The first argument, ap
, is a va_list
object that was previously initialized using va_start()
. The second argument is the type of the argument that you want to retrieve.
The va_arg()
macro returns the next argument in the list as the specified type. It also advances the va_list
object to the next argument in the list, so that subsequent calls to va_arg()
will retrieve the remaining arguments in the list.
Here's an example of how to use va_arg()
to retrieve a variable number of integer arguments from a va_list
object:
#include <stdarg.h> int sum(int num_args, ...) { va_list ap; int arg, total = 0; va_start(ap, num_args); for (int i = 0; i < num_args; i++) { arg = va_arg(ap, int); total += arg; } va_end(ap); return total; }
In the above example, the sum()
function takes a variable number of integer arguments, with the first argument specifying the number of arguments to follow. The va_list
object ap
is initialized using va_start()
to point to the first argument in the list. The va_arg()
macro is then used to retrieve each subsequent argument, one at a time, and add it to the total
variable. Finally, the va_end()
macro is called to free any resources associated with the va_list
object.