0

I need to distinguish the three forms:

#define CONSTANTNAME

#define CONSTANTNAME 0

#define CONSTANTNAME 1

I saw someone use the hint:

#if (CONSTANTNAME - 0)

but this confuse the form without value and the one with 0.

Is there something smarter?

efa
  • 1
  • 1

1 Answers1

0

Can I assume you want the empty definition and the 1 definition to be equivalent with the 0 is the different one? I'm pretty sure that question already exists on stackoverflow, but I can't find it.

Here's a usenet thread on the same topic: https://groups.google.com/d/msg/comp.lang.c/jkI2vz8ZxmE/1-kOKCQ2MrwJ

Several answers are given there. The cleverest one looks like:

#if -CONSTANTNAME+1 == 1
... the "no CONSTANTNAME" branch
#else
... the "yes CONSTANTNAME" branch
#endif

If CONSTANTNAME is empty, -+1 == 1 => false.

If it's 1, -1+1 == 1 => false.

If it's 0, -0+1 == 1 => true.

If it's not defined, the default cpp replacement for unrecognized tokens applies, and that's a 0 so it's true.

UPDATE

If you want 3 branches, you can still use the -FOO+0 == 1 test and add an extra test like FOO+0==0. Look at the results you can get:

Value of `FOO`   `-FOO+1==1`   `FOO+0==0`
 empty string         false         true
            1         false        false
            0          true         true

If the 4th case, macro not defined, is interesting, it must be tested with #ifdef FOO or defined(FOO) since it is otherwise indistinguishable from 0.

Sample code:

#if !defined(FOO)
... handle undef
#elif -FOO+1 == 1
... handle 0
#elif FOO+0 == 0
... handle empty
#else
... handle 1
#endif
  • I need to follow three different branches for the three cases listed in question – efa Dec 26 '13 at 14:07