delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/08/22/19:54:48

Sender: nate AT cartsys DOT com
Message-ID: <35DF1B94.BBE4EBC4@cartsys.com>
Date: Sat, 22 Aug 1998 12:27:16 -0700
From: Nate Eldredge <nate AT cartsys DOT com>
MIME-Version: 1.0
To: brentlinger DOT 4 AT osu DOT edu
CC: djgpp AT delorie DOT com
Subject: Re: trouble with ellipes in functions
References: <35D5B0EE DOT 1E94 AT osu DOT edu>

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019