<stdarg.h> - variable
arguments
jump to: demonstration of <stdarg.h>
The header provides funtions that allow the programmer
to write functions containing variable-lenght paramater
lists. The variable argument list macros provide a portable
method of accessing arguments to a function taking a variable
number of arguments.
| type va_arg(va_list argptr, type); |
returns the current and succeeding arguments |
| void va_end(va_list argptr); |
sets the argument pointer to NULL |
| void va_start(va_list argptr); |
sets the argument poointer (argptr), declared as type
va_list, to the first argument in the list passed to
the function |
| |
|
The <stdarg.h> header contains a
set of macros which allows portable functions that accept
variable argument lists to be written. Functions that have
variable argument lists (such as printf()) but do not use
these macros are inherently non-portable, as different systems
use different argument-passing conventions.
The type va_list is defined for variables used to traverse
the list.
The va_start() macro is invoked to initialise ap to the
beginning of the list before any calls to va_arg().
The object argptr may be passed as an argument to another
function; if that function invokes the va_arg() macro with
parameter argptr, the value of argptr in the calling function
is indeterminate and must be passed to the va_end() macro
prior to any further reference to argptr. The parameter
argN is the identifier of the rightmost parameter in the
variable parameter list in the function definition (the
one just before the , ...). If the parameter argN is declared
with the register storage class, with a function type or
array type, or with a type that is not compatible with the
type that results after application of the default argument
promotions, the behaviour is undefined.
The va_arg() macro will return the next argument in the
list pointed to by argptr. Each invocation of va_arg() modifies
argptr so that the values of successive arguments are returned
in turn. The type parameter is the type the argument is
expected to be. This is the type name specified such that
the type of a pointer to an object that has the specified
type can be obtained simply by suffixing a * to type. Different
types can be mixed, but it is up to the routine to know
what type of argument is expected.
The va_end() macro is used to clean up; it invalidates
argptr for use (unless va_start() is invoked again).
Multiple traversals, each bracketed by va_start() va_end(),
are possible.
Example:
#include <stdarg.h>
#define MAXARGS 31
int execl (const char *file, const char *args, ...)
{
va_list ap;
char *array[MAXARGS];
int argno = 0;
va_start(ap, args);
while (args != 0) {
array[argno++]
= args;
args =
va_arg(ap, const char *);
}
va_end(ap);
return execv(file, array);
}
go to <stddef.h> back
to top back
to main