Using Macros

Checkpoint Technologies ckp at grebyn.com
Thu Aug 9 01:30:05 AEST 1990


In article <362.26be9dcc at astro.pc.ab.com> yoke at astro.pc.ab.com (Michael Yoke) writes:
>Could some of you give me your opinion on the best way to handle multiple 
>statement macros.
> [then asks about a multi-statement macro that works like a statement
>  ought to]

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.

I'll give an example of a macro I use a lot.  It's a derivative of
"strncpy" which assures a zero terminator on the destination (strncpy
doesn't) and which measures the destination length itself, using
sizeof:

#define STRMOV(dest,src) \
      ((void) strncpy(dest, src, sizeof(dest)-1), \
      dest[sizeof(dest)-1] = '\0', \
      dest)

Note three expressions, all separated by commas.  The result type and
value of the comma operator is the type and value of the second
expression, so the STRMOV macro "returns" the value "dest" of it's type.
(I actually use one that "returns" type "void"; the return value from
strncpy always puzzled me.)

Note also for this macro to work, the type of dest must be "array [known
size] of char", not "pointer to char" or "array [unspecified size] of
char".

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.
-- 
First comes the logo: C H E C K P O I N T  T E C H N O L O G I E S      / /  
                                                                    \\ / /    
Then, the disclaimer:  All expressed opinions are, indeed, opinions. \  / o
Now for the witty part:    I'm pink, therefore, I'm spam!             \/



More information about the Comp.lang.c mailing list