delorie.com/djgpp/doc/libc/libc_849.html | search |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
#include <stdarg.h> void va_start(va_list ap, LAST_REQUIRED_ARG); TYPE va_arg(va_list ap, TYPE); void va_end(va_list ap); |
Used to write functions taking a variable number of arguments. Note that these are actually macros, and not functions. You must prototype the function with `...' in its argument list. Then, you do the following:
Create a variable of type va_list
.
Initialize it by calling va_start
with it and the name of the
last required (i.e. non-variable) argument.
Retrieve the arguments by calling va_arg
with the
va_list
variable and the type of the argument. As another
alternative, you can pass the va_list
to another function,
which may then use va_arg
to get at the arguments.
vprintf
is an example of this.
Call va_end
to destroy the va_list
.
Be aware that your function must have some way to determine the number
and types of the arguments. Usually this comes from one of the required
arguments. Some popular ways are to pass a count, or to pass some
special value (like NULL
) at the end.
Also, the variable arguments will be promoted according to standard C
promotion rules. Arguments of type char
and short
will
be promoted to int
, and you should retrieve them as such. Those
of type float
will be promoted to double
.
va_arg
returns the argument it fetched, the other macros return nothing.
ANSI/ISO C | C89; C99 |
POSIX | 1003.2-1992; 1003.1-2001 |
int find_the_sum(int count, ...) { va_list ap; int i; int total = 0; va_start(ap, count); for (i = 0; i < count; i++) total += va_arg(ap, int); va_end(ap); return total; } int other_function(void) { return find_the_sum(6, 1, 2, 3, 4, 5, 6); } |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
webmaster | delorie software privacy |
Copyright © 2004 | Updated Apr 2004 |