Mail Archives: djgpp/1998/08/22/19:54:48
brentlinger DOT 4 AT osu DOT edu wrote:
>
> I'm writing a function that needs a varible numder of inputs ie (,...)
> but I can,t seem to get it to work. Could someone post the sources to
> printf() or a similar example?
Here is a copy of the docs I wrote for the variadic macros. They will
be included in 2.02.
va_*
====
Syntax
------
#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);
Description
-----------
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'.
Return Value
------------
`va_arg' returns the argument it fetched, the other macros return
nothing.
Example
-------
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);
}
Hope this helps.
--
Nate Eldredge
nate AT cartsys DOT com
- Raw text -