4

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?

2

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Equal to zero, or be an empty token sequence?
@StoryTeller I've read somewhere that in such a context it's equal to zero. I'll try to dig something up.
Empty token sequence in #if comparision is equal to zero
@Someprogrammerdude - Now I read it too :) port70.net/~nsz/c/c11/n1570.html#6.10.1p4
@StoryTeller From cppreference: "Any identifier, which is not literal, non defined using #define directive, evaluates to 0."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.