Variable number of arguments to a function

Andrew Koenig ark at alice.UUCP
Mon May 7 00:05:13 AEST 1990


In article <3697 at iitmax.IIT.EDU>, thssvhj at iitmax.IIT.EDU (vijay hemraj jadhwani) writes:

> myprint(stream, fmt, a1, a2, a3, a4, a5)  /* Function definition */
> FILE *stream;
> char *fmt;
> {
> 	... some initialization and assignment ...
> 	sprintf(stream, fmt, a1, a2, a3, a4, a5);
> 			.
> 			.
> 			.
> }

> 1. Which of the above 3 cases are correct and which are not? Why ?

None of them.  The myprint() function itself is non-portable and
in fact will not work on many implementations.

> 2. If I want to remove any "lint" warnings, for argument number mismatch,
>    what should I do ? i.e. I need a scheme to be able to pass variable
>   number of arguments to myprint(). Also it would be nice , if I could 
>   also have an ability to  pass any "type" of arguments to myprint().

If you want something that works, and not just something that shuts
lint up, you must use either <varargs.h> or <stdarg.h> for an ANSI C
implementation.  You must also use vfprintf, which interfaces explicitly
with <varargs.h> or <stdarg.h>.  Example:

	#include <varargs.h>

	myprint(va_alist) va_dcl
	{
		va_list ap;
		FILE *stream;
		char *fmt;

		va_start(ap);
		stream = va_arg(ap, FILE *);
		fmt = va_arg(ap, FILE *);

		/* ... some initialization and assignment ... */

		vsprintf(stream, fmt, ap);
				
		/* and so on */
	}
-- 
				--Andrew Koenig
				  ark at europa.att.com



More information about the Comp.lang.c mailing list