3

Before I define a macro function, I can check that it doesn't already exist
(this avoids overwriting a previous definition).

I can implement the check and definition like this:

#ifndef MACRO(X)
#define MACRO(X) FUNCTION(X)
#endif

Or like this:

#ifndef MACRO
#define MACRO(X) FUNCTION(X)
#endif

Both appear to work when the function is already defined.
So, which is correct? Which is preferred?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271

2 Answers2

7

Without.

The standard specifies that #ifndef is equivalent to #if !defined, and that the argument to defined must be a (possibly parenthesized) identifier. You can't have parens in an identifier, so defined MACRO(X) is not an allowed form. This use of defined causes undefined behaviour, so it is not portable.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
2

Without parentheses. Because of this reason:

test.c

#ifdef MACRO(x)
#endif
int main() {}

If you try to compile this:

$ gcc test.c
test.c:2:13: warning: extra tokens at end of #ifdef directive [enabled by default]
 #ifdef MACRO(x)
             ^

It gives a warning.

e0k
  • 6,961
  • 2
  • 23
  • 30