C Questions

David M. Read readdm at walt.cc.utexas.edu
Wed Oct 25 05:04:13 AEST 1989


In article <1248 at utkcs2.cs.utk.edu> wozniak at utkux1.utk.edu (Bryon Lape) writes:
>
>	I have 2 questions concerning function definitions:  How does
>one write a function so that some, not all, or the items passed can be
>any type of variable at any time?  How does one write a function so that
>any number of variables can be sent?
>

The best way I know of to handle both problems is with a variable argument
list, which is covered under ANSI C.  It works like this:

#include  <stdarg.h>

func_1 (int parm1,
        int parm2,
        ...)
{
   va_list arg_list;
   int      junk;

   va_start (parmN, va_list);

   junk = va_arg (va_list, int);

   va_end (va_list);
}

Clearly, any type of variable can be passed, but you need to know several
things to use va_arg:
1) The type of the next variable on the list
2) How many variables there are in total.
Both of these can be determined from a format string passed to the function
(as in printf()).

In the above code, parmN refers to the LAST of the known parameters in the
declaration (you must have at least one which is known).  The parameters
parm1, parm2, ... , parmN may be of any type.
Call va_arg once for each variable in the list, with the correct type.
Be sure to call va_end when you're done or you get funny gremlins later on.

I have been doing a bunch of variable argument-list processing recently, so
I can show you actual working source code if you like.


----------------------------------------------------------------------------
David M. Read                        best -=>  readdm at walt.cc.utexas.edu
                           all-else-fails -=>  read at physics.utexas.edu

"...[he's] stupid and he's ignorant but he's got guts...and guts is enough!"
----------------------------------------------------------------------------



More information about the Comp.lang.c mailing list