C++ #if#elif#endif 似乎不起作用

标签 c++ if-statement c-preprocessor preprocessor-directive

有人可以告诉我我做错了什么吗?

#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

这当然是真的。

预处理器表达式中的 == 运算符不比较字符串或标识符,它只比较整数表达式。您可以通过为 ABmyvar 定义整数值来完成您想做的事情,例如:

#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/

相关文章:

c++ - 程序内存问题

javascript - 如何检查文本框是否被点击

c++ - 头文件在整个程序中仅包含一次?

objective-c - iPhone项目常数

c++ - 在构建服务器上处理多个 Windows SDK 版本

c++ - 尝试使用 boost::interprocess::message_queue 时出现 library_error 异常

c++ - 如何在 IDL 中声明 IN、OPTIONAL 参数以及 OUT、RETVAL 参数

javascript - 如果 ("!" bool 函数())

javascript - 为什么我的函数没有按预期显示和隐藏元素?

c - 解释一下为什么代码编译成功