passing variable arguments

Daniel E. Platt platt at ndla.UUCP
Mon Jun 11 23:43:49 AEST 1990


In article <353 at ankh.ftl.fl.us>, chin at ankh.ftl.fl.us (Albert Chin) writes:
> How does printf() work. I believe there is some way in C to obtain the
> pointer to the argument list in a function. If so, printf() is pretty 
> simple. But how do you do this. Is it possible to get the number of
> arguments in a printf() statement?



If you have a function 'foo', defined:

void	foo(a, b, c)
char	a, b, c;
{
	char	*pt;

	/* get a pointer to the stack */
	pt = &a;

	/* 
	**	Then:
	**		pt[0] <-> a;
	**		pt[1] <-> b;
	**		pt[2] <-> c;
	*/

	...
}

C is set up to put the first argument on the top of the 'stack' (if
there is one).  Then in the case of 'printf', you can get the number
of arguments by counting the number of  '%'s (actually, you have to be a
bit careful since '%%' is the symbol for the character '%').  Types, and
therefore implementation defined sizes, are determined from what follows
the % escape.

It turns out that you have to be careful about sizes of things, and this
isn't portable.  There are macro standards set up to handle this called
'varargs.'  


Hope this helps,

Dan



More information about the Comp.lang.c mailing list