Varargs for Macros?

Alan_T._Cote.OsbuSouth at Xerox.COM Alan_T._Cote.OsbuSouth at Xerox.COM
Sun Feb 21 11:03:07 AEST 1988


Dan Kegel <dan at srs.uucp> writes,

>For example, I'd like to have a macro that calls write() and prints a fancy
>error message upon failure.  It would expand this
>  WRITE(fd, buf, bytes, "Error at record %d of %s", recNum, fileName);
>to this:
>  if (write(fd, buf, bytes) != bytes)
>     fprintf(stderr, "Error at record %d of %s", recNum, fileName), exit(1);
>regardless of the number of arguments to fprintf.

If you're willing to modify your example just a little, you can get what you
want.  Try this macro:

#define WRITE(fd,buf,bytes,errparm) \
        if(write(fd,buf,bytes)!=bytes) \
          fprintf errparm, exit(1)

Here's a sample call:

WRITE(fd, buf, bytes, (stderr,"Error at record %d of %s", recNum, fileName));

Which should generate:

if(write(fd,buf,bytes)!=bytes)
        fprintf (stderr,"Error at record %d of %s", recNum, fileName), exit(1);

The trick is in the use of parentheses.

Neat, huh?!?

	- Al Cote'

PS:  No flames for tasteless style -- this is only a quickie!!



More information about the Comp.lang.c mailing list