Jack Trades said:
[...]> Macros just do text replacement. Â The main safety measure is to put
all parameters and the entire result in parens so you don't get
unexpected associativity problems.
[...]
My usual HHGTTG-inspired horrible example is:
#include <stdio.h>
#define SIX 1+5
#define NINE 8+1
int main(void)
{
  printf("%d * %d = %d\n", SIX, NINE, SIX * NINE);
  return 0;
}
Which would become 1+5*8+1 and return 42?
I'm assuming that in addition to order of operations issues there is
also a problem with variable capture as is the case with LISP style
macros? I know this is probably a stupid question but are there any
third-party hygenic macro packages available for C?
I'm not quite sure what "variable capture" is, but I don't think it
applies. Macro expansion is in effect another language layered on top
of C. The preprocessor has no awareness of C expressions; it operates
entirely on sequences of tokens. The macro SIX expands to a sequence of
three tokens, ``1'', ``+'', and ``5''; similarly for NINE. A later
phase of translation then sees the resulting token sequence:
printf ( "%d * %d = %d\n" , 1 + 5 , 8 + 1 , 1 + 5 * 8 + 1 ) ;
I'm not sure what a "third-party hygenic macro package" would look like.
When you're writing and using macros, you just have to be careful to
follow a few guidelines. Use all-caps names as a reminder that the
thing you're using is a macro and not a function. For macros to be used
in place of expressions, make sure each argument reference is
parenthesized, as is the entire definition. For example:
#define SQUARE(x) ((x) * (x))
For macros that play tricks with the syntax, it's not always so simple,
and you have to be *really* careful.