Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "#if Foo - 0 == 0" and "#if defined(Foo) && Foo == 0"?

Find this in the qt documentation. What is the difference between

#if defined(Foo) && Foo ==  0

and

#if Foo - 0 ==  0

As far as I understand the latter also will be false if Foo is undefined? Where can I read about this?

like image 829
Hate Avatar asked Jan 04 '13 23:01

Hate


2 Answers

If Foo is undefined, then the latter will translate to

#if 0 - 0 == 0

which is true, not false. Remember that under #if all undefined identifiers are replaced with literal 0 (once all defined() operators are evaluated, of course). That applies even to preprocessing tokens that match language keywords. In C language all keywords are replaced with 0 in this context. In C++ keywords true and false are exempt from replacement, while all other keywords are replaced.

(BTW, that means that in C true will be quietly replaced with 0 if <stdbool.h> is not included, and with 1 if <stdbool.h> is included.)

Meanwhile

#if defined(Foo) && Foo == 0

is false when Foo is undefined. So, here's your difference.

The Qt documentation does indeed seem to suggest that the former is the same as the latter. I don't know why they do that, since they are certainly not equivalent. It appears to be an error in Qt docs.

like image 130
AnT Avatar answered Oct 22 '22 02:10

AnT


Difference between Foo == 0 and Foo - 0 == 0 is that in the former, Foo must be defined with a value:

#define Foo 0

and cannot be:

#define Foo  //  Foo == 0 would give an error, cannot evaluate Foo

While in the case of Foo - 0 == 0, Foo can be defined without a value

So:

#if defined(Foo) && Foo ==  0

Means Foo defined and it has a value (of 0 in this case).

and:

#if Foo - 0 ==  0

Means Foo is either defined with 0 or defined without a value, but since it doesn't have the defined(Foo) like in the first case, Foo undefined would apply as well.

like image 41
StackHeapCollision Avatar answered Oct 22 '22 00:10

StackHeapCollision