home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!haven.umd.edu!mimsy!peyote
- From: peyote@umiacs.umd.edu (Gary W. Flake)
- Newsgroups: comp.lang.c
- Subject: Re: Variable arguments & macros...
- Keywords: macros, varargs
- Message-ID: <59160@mimsy.umd.edu>
- Date: 22 Jul 92 13:18:06 GMT
- References: <markkj.711771545@munagin>
- Sender: news@mimsy.umd.edu
- Organization: UMIACS, University of Maryland, College Park, MD 20742
- Lines: 66
-
- markkj@mullian.ee.mu.OZ.AU (Mark Johnston) writes:
- >
- > I'm wondering if anyone has any really devious ways of writing macros
- >so that variable arguments can be used. The problem is that I have a function
- >that does error handling for a program, and it takes variable arguments:
- >
- >int writeErrorMsg(int quit, char *file, int line, char *format, ...)
- >{
- > /* ... */
- >}
- > The macros are:
- >
- >#define error(x) writeErrorMsg(0, __FILE__, __LINE__, x)
- >#define fatal(x) writeErrorMsg(1, __FILE__, __LINE__, x)
- >
- >
- > Last but not least, I'm using the functions in the following way:
- >
- > error("The error code is %1d.", errCode);
- >
-
-
- I wouldn't recommend this for everyone but...
-
- MERGE(x,y) will exand both x and y THEN concat them. There are other
- ways to doing this, but this is the only one that has always worked
- for me.
-
- #define MERGE(x,y) MERGE ## _KLUDGE(x,y)
- #define MERGE_KLUDGE(x,y) x ## y
-
- now...
-
- #define ARG(x) , (x)
- #define __ARG(x) (x)
- #define error(x) writeErrorMsg(0, __FILE__, __LINE__, MERGE(__,x))
- #define fatal(x) writeErrorMsg(1, __FILE__, __LINE__, MERGE(__,x))
-
- The variable argument portion of the macro should have no commas, e.g.
-
- error(ARG("foo = %d -- bar = %d) ARG(fooness) ARG(barness));
-
- expands too:
-
- writeErrorMsg(0, "foo.c", 666,
- MERGE(__, ARG("foo = %d -- bar = %d") ARG(fooness) ARG(barness))
-
- ->
-
- writeErrorMsg(0, "foo.c", 666,
- __ARG("foo = %d -- bar = %d) ARG(fooness) ARG(barness))
-
- ->
-
- writeErrorMsg(0, "foo.c", 666, ("foo = %d -- bar = %d), (fooness), (barness))
-
-
- This'll work in gcc.
-
- Don't you just love the preprocesser!
-
- Cheers,
- Gary
- --
- Spoken: Gary W. Flake Domain: peyote@umiacs.umd.edu UUCP: uunet!mimsy!peyote
- Phone: +1-301-405-6757 USPS: UMIACS, U. of Maryland, College Park, MD 20742
-