Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 740
user1229731 Avatar asked Sep 12 '26 11:09

user1229731


1 Answers

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.

like image 59
M.M Avatar answered Sep 14 '26 01:09

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!