Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!usc!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!ames!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Variable number of arguments to a function Keywords: c, variable number of arguments, sprintf Message-ID: <24223@mimsy.umd.edu> Date: 6 May 90 08:45:32 GMT References: <3697@iitmax.IIT.EDU> Distribution: na Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 73 In article <3697@iitmax.IIT.EDU> thssvhj@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 : /* complete source for a working printf() */ #include #include 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 #include 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 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@cs.umd.edu Path: uunet!mimsy!chris