Using Macros

Brad Appleton brad at SSD.CSD.HARRIS.COM
Thu Aug 9 07:19:31 AEST 1990


In article <21057 at grebyn.com> ckp at grebyn.UUCP (Checkpoint Technologies) writes:
>
>If each "statement" in the macro is really an "expression", then you can
>use the comma operator to make them all into one expression, which then
>serves as one statement.  This can even be used to make multi-expression
>macros that appear (mostly) to be function calls as well, so long as you
>can engineer the "return value" to be the last expression in the comma-
>separated list.
>
>Now this technique won't work if you really need multiple "statements",
>which could include things like return, break, if, while, etc., but it
>works just dandy for multiple expressions.

Glad to see a few people finally mentioned the comma operator! Another 
alternative along those same lines (with similar limitations) is to make
use of the logical operators || and &&. Using this, the following:

	#define CHECK(cond)  { if (cond)  exit(-1);  }

could be replaced by

	#define CHECK(cond)  ((cond) || exit(-1))

And wouldnt wreak havoc inside nested if statements.

As another example, if you didnt have the dup2() system call on your Unix
system and wanted to write a macro for it, you could use the following:

    #define  dup2(to,from)  ( (close(from) || (to = dup()) < 0) ? -1 : 0 )

If there is some reason why this would not give the same results as dup2()
(and fail for the same reasons) then let me know. The main problem I foresee
is that I cant have a file-descriptor numbered lower than `from' available
before I make the dup2() call.

Anyway, even if the results from the above are totally incorrect, it still
demonstrates the use of logical operators in macros.

Hope this helps!
______________________ "And miles to go before I sleep." ______________________
 Brad Appleton        brad at travis.ssd.csd.harris.com   Harris Computer Systems
                          ...!uunet!hcx1!brad          Fort Lauderdale, FL USA
~~~~~~~~~~~~~~~~~~~~ Disclaimer: I said it, not my company! ~~~~~~~~~~~~~~~~~~~
______________________ "And miles to go before I sleep." ______________________
 Brad Appleton        brad at travis.ssd.csd.harris.com   Harris Computer Systems
                          ...!uunet!hcx1!brad          Fort Lauderdale, FL USA
~~~~~~~~~~~~~~~~~~~~ Disclaimer: I said it, not my company! ~~~~~~~~~~~~~~~~~~~



More information about the Comp.lang.c mailing list