James wrote:

> how do i create a function that has an undetermined number of parameters?
> i.e printf can have 1 parameter:
> 
>       printf ("Hello World\n");
> 
> or many...
> 
>       printf ("Hello","world","\n","%d%d%d", 2, 0, 35);

This isn't a legitimate printf() call. The format string has to be a
single argument, e.g.

        printf("Hello world \n%d%d%d", 2, 0, 35);

> how?

By using an ellipsis (`...') in the declaration and using the
va_{start,arg,end} macros (defined in stdarg.h) to access the
parameters.

> the definition for it has '...' as a parameter... what's that mean?

It means `plus any number of extra parameters'.

> and if you don't know how many parameters are being passed into the
> function beforehand, how do you know what the variable names are?

You don't. You need to use the va_* macros to access the additional
parameters.

You also need to be able to figure out how many parameters should have
been passed, and what their types are. printf() determines this from
the format string. Other possibilities include having a count
parameter and using a NULL argument to terminate the list (as is the
case for execl() and friends, and the XtVa* functions).

For example:

        #include <stdarg.h>
        #include <stdio.h>

        void contrived(int count, ...)
        {
                va_list va;
                int i;

                va_start(va, count);

                for (i = 0; i < count; i++)
                        printf("%s\n", va_arg(va, char *));

                va_end(va);
        }

        int main(void)
        {
                contrived(3, "hello", "there", "world");
                return 0;
        }

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to