Variable number of arguments to a function

Chris Torek chris at mimsy.umd.edu
Sun May 6 18:45:32 AEST 1990


In article <3697 at iitmax.IIT.EDU> thssvhj at iitmax.IIT.EDU
(vijay hemraj jadhwani) writes:
[code examples deleted]
>Case 1. ACTUAL NO. OF ARGUMENTS < NO. OF ARGUMENTS IN THE FUNC. DEFINITION
>Case 2.  ACTUAL NO. OF ARGUMENTS > NO. OF ARGUMENTS IN THE FUNC. DEFINITION
>Case 3: ARGUMENT TYPE IS DIFFERENT THAN THE EXPECTED ARGUMENT TYPE
>1. Which of the above 3 cases are correct and which are not? Why ?

All are incorrect.  In C, every function call must match the function
definition in both number and types of arguments.  In Classic C, there
is no escape mechanism, yet printf() manages the trick: it uses an
`almost-standard' method involving <varargs.h>:

	/* complete source for a working printf() */

	#include <stdio.h>
	#include <varargs.h>

	int printf(va_alist)
		va_dcl
	{
		char *fmt;
		int ret;
		va_list ap;

		va_start(ap);
		fmt = va_arg(ap, char *);
		ret = vfprintf(stdout, fmt, ap);
		va_end(ap);
		return ret;
	}

(The above requires that your C library include the vfprintf() function;
some do not.  If not, you are out of luck, because these same systems
lack vsprintf, which is the function everyone writing `myprint' routines
always ends up using for portability.)

In New C (i.e., implementations claiming conformance to ANSI X3.159-1989)
there is an explicit escape mechanism using <stdarg.h.:

	/* revised working printf() */

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

	int printf(char const *fmt, ...) {
		int ret;
		va_list ap;

		va_start(ap, fmt);
		ret = vfprintf(stdout, fmt, ap);
		va_end(ap);
		return ret;
	}

The three dots in the parameter list declaration tell the compiler
`the rest of the arguments are weird, like those to printf()'.  The
compiler stops applying type checking, and may use an entirely different
calling sequence.

>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().

Write a myprintf() along the lines shown in the second example above.
If your `lint' does not claim conformance to ANSI X3.159-1989 (`ANSI C'),
this option will not be available.  The way to `fool' lint when using
the old-style <varargs.h> file is more complicated, and depends on
exactly which lint bugs are in your lint variant.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list