有人可以告诉我我做错了什么吗?
#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
}
输出是 A 但显然我期待 B
最佳答案
这个:
#if myvar == A
扩展为:
#if B == A
引用C++标准:
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.
所以这等同于:
#if 0 == 0
这当然是真的。
预处理器表达式中的 ==
运算符不比较字符串或标识符,它只比较整数表达式。您可以通过为 A
、B
和 myvar
定义整数值来完成您想做的事情,例如:
#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
关于C++ #if#elif#endif 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204792/