gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:36:12 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com