Search code examples
c++c-preprocessorpreprocessor-directive

Preprocessor test for equality always evaluates true


Using this:

-DME=AWESOME

and this:

#if ME==AWESOME

#error Im awesome!

#endif

yields this:

Registers.cpp:59:2: error: #error Im awesome!

but this:

#if ME==NOTSOGREAT

#error Im confused!

#endif

yields this:

Registers.cpp:59:2: error: #error Im confused!


Solution

  • Note that doing -DME=AWESOME is equivalent to your source file starting with:

    #define ME AWESOME
    

    Now let's look at #if ME==AWESOME. Token replacement changes ME to AWESOME, so the final version of this line is:

    #if AWESOME==AWESOME
    

    When you use == in the preprocessor, an alphabetic token that is not #defined to anything else, gets replaced by 0. So this tests #if 0 == 0 which is true, so your error is displayed.

    Now, looking at:

    #if ME==NOTSOGREAT
    

    After token replacement it is:

    #if AWESOME==NOTSOGREAT
    

    which again is equivalent to #if 0 == 0, which is true.


    If you also had #define AWESOME 5 before this, then you would find that the first test is true but the second test is false.

    I guess you are trying to detect if ME had been defined to AWESOME but there is no way to do that; you can only test whether ME has been defined as something equal to whatever AWESOME has been defined as.