Question

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

Était-ce utile?

La 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

Autres conseils

try

int main(void) {
    #define myvar 2
    #if myvar == 1
            std::cout << "A" << std::endl;
    #elif myvar == 2
            std::cout << "B" << std::endl;
    #else
            std::cout << "Neither" << std::endl;
    #endif
    return 0;
}

More details please refer to the following link

http://msdn.microsoft.com/en-us/library/ew2hz0yd.aspx

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top