Search code examples
c++if-statementc-preprocessorpreprocessor-directive

C++ #if #elif #endif don't seem to work


Can somebody please tell me what I'm doing wrong?

#include <iostream>
using namespace std;

int main() {

#define myvar B

#if myvar == A
        cout << "A" << endl;
#elif myvar == B
        cout << "B" << endl;
#else
        cout << "Neither" << endl;
#endif
}

The output is A but obviously I was expecting B


Solution

  • This:

    #if myvar == A
    

    expands to:

    #if B == A
    

    Quoting the C++ standard:

    After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers and keywords, except for true and false, are replaced with the pp-number 0, and then each preprocessing token is converted into a token.

    so that's equivalent to:

    #if 0 == 0
    

    which is of course true.

    The == operator in preprocessor expressions doesn't compare strings or identifiers, it only compares integer expressions. You can do what you're trying to do by defining integer values for A, B, and myvar, for example:

    #define A 1
    #define B 2
    #define myvar B
    
    #if myvar == A
        cout << "A" << endl;
    #elif myvar == B
        cout << "B" << endl;
    #else
        cout << "Neither" << endl;
    #endif