James Wilkinson wrote:
> 
> On Fri, 12 May 2000, Alex generated:
> 
> > Wayne wrote:
> >>     void log_msg(char *fmt, ...)
> >>     {
> >>         FILE *fd = fopen("/tmp/mylog", "a");
> >>         va_list arglist;
> >>
> >>         va_start(arglist, fmt);
> >>         vfprintf(fd, fmt, arglist);
> >>         fclose(fd);
> >>     }
> >I'm not familiar with vs_list and va_start (though I can guess that
> >vfprintf() is probably a variant of fprintf()), could you give a brief
> >explanation?

This is how you pass a variable number of arguments to a function
(actually, there is a line missing 'va_end(arglist);' which should be
after the vfprintf call). The variable list is represented in the
function prototype by the '...'.

vfprintf is a variant of fprintf that accepts its inputs as a va_list.

> Basically, you can specify a variable number of arguments to functions,
> the compiler does some magic and this comes as a pointer to an array of
> char *'s.

The va_list type does seem to be a pointer to a list of some type. I
haven't investigated it to see if they are actually char pointers. The
arguments as passed to the log_msg function above would just be placed
on the stack in the usual C fashion (right to left), so the top of the
stack holds the first argument(s), at least one of which must enable the
function to work out how many arguments are in the variable section. The
va_start and va_end functions are actually macros. I don't know what
they do exactly, but I expect that they would pop the remaining
arguments from the stack and put them into the va_list pointer array.

> ... this is where the format string in *printf come in, it parses
> the string for % characters and replaces them with the contents of the
> next argument in the list.  Needless to say, the type of the argument
> must match the type given in the format string.

Yes, this is how *printf works out how many arguments it needs to get
from the stack.

Matthew
--
SLUG - Sydney Linux Users Group Mailing List - http://www.slug.org.au
To unsubscribe send email to [EMAIL PROTECTED] with
unsubscribe in the text

Reply via email to