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

有帮助吗?

解决方案

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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top