Variable Numbers of Args to Functions in ANSI C.

Jeff Kellem composer at bu-cs.BU.EDU
Mon May 1 23:05:24 AEST 1989


In article <13024 at paris.ics.uci.edu> sklein at bonnie.ics.uci.edu (Steve Klein) writes:
>If I forward-declare the function:
>
>	int func(a, b, ...);
>
>Then how do I define and call 'func'?
>
>I tried:
>    	#include <varargs.h>
>
>    	int func(a, b, va_alist);
>    	int a, b;
>    	va_dcl
>    	{
>    	    ...
>    	}
>
>but GNU CC says 'number of args doesn't match prototype'.

GCC is correct with this.  For one, <varargs.h> is not (as far as I know)
part of the ANSI standard.  What you want to use is <stdarg.h>.

So, basically what you want in ANSI C for the above is something like the
following: 

	#include <stdarg.h>

	int func(int, int, ...);

	...

	int func(int a, int b, ...)
	{
	   va_list arg_pointer;
	   int foo;
	 ...
	/* Then in here, call va_start(arg_pointer, b); */
	/*   to initialize the argument pointer to the optional */
	/*   parameter list. */

	   va_start(arg_pointer, b);

	/* Successive calls to va_arg will get the remaining args. */

	   foo = va_arg(arg_pointer, int);

	/* Then, finally call va_end to reset everything back to normal. */

	   va_end(arg_pointer);
	 ...
	}
	
Hope this helps ... Enjoy ...


                               -jeff

Jeff Kellem
INTERNET: composer at bu-cs.bu.edu  (or composer%bu-cs.bu.edu at bu-it.bu.edu)
UUCP: ...!harvard!bu-cs!composer



More information about the Comp.std.c mailing list