Emanuele Paolini
Emanuele Paolini

Reputation: 10162

using enum values in preprocessor directive

I have the following code:

#include <stdio.h>

enum {A, B};

#define C A

int main() {
#if C == B
  printf("%d==%d\n", C, B);
#else
  printf("%d!=%d\n", C, B);
#endif
}

which, surprinsingly, gives the output:

0==1

Now, I understand that the code is wrong, because enum values are unknown to the preprocessor. What I don't understand is why no error is generated... A and B should be undefined at preprocessing time, how is that the preprocessor gives no error?

Upvotes: 4

Views: 2305

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

The preprocessor runs in a separate phase before the compiler proper handles the source. As such it doesn't know anything about symbols in the actual source code (like enumerations or variables).

For the preprocessor the symbol B is an unknown macro and when used in that context (#if C == B) it will be equal to zero. Since the symbol A is also not a macro, it will also evaluate to zero. All this lease to the comparison #if 0 == 0 which is indeed true.

See e.g. this phases of translation reference for more information about translation phases, and this preprocessor conditional reference for more information about that.

Upvotes: 9

Related Questions