Args: var number & var types
Karl Heuer
karl at haddock.ISC.COM
Fri May 13 04:38:05 AEST 1988
In article <cWW=o4y00XcRh2E04h at andrew.cmu.edu> jv0l+ at andrew.cmu.edu (Justin Chris Vallon) writes:
>Is there any way to declare a function to have two arguments point to the
>same place in the stack-frame? Let's say that I want to write [a function]
>foo which takes an optional argument based upon the first parameter: ...
> foo(0); /* no optional argument */
> foo(1, c); /* pass a character argument */
> foo(2, i); /* pass an integer argument */
> foo(3, s); /* pass a short arg */
> foo(4, l); /* pass a long arg */
> foo(5, "Hello world"); /* pass a char* arg */
Yes, it can be done, in at least two ways. Doug Gwyn has suggested using
unions; this is awkward because (lacking a cast-to-union) you'd have to write
junk like "un.u_asint = i; foo(2, un);". The other way is to use <stdarg.h>
(on ANSI implementations) or <varargs.h> (if you've got it). In this case you
don't declare the second argument at all, but instead fetch its value from the
argument list via the va_arg macro.
N.B. When function foo() handles cases 1 and 3, the argument type must be
specified as "int", even if you want to store it in a smaller object:
char c; ...
c = va_arg(ap, int);
Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint
More information about the Comp.lang.c
mailing list