fek*_*lee 0 c++ gcc preprocessor g++ c-preprocessor
foo.cpp:
#define ID A
#if ID == A
#warning "hello, world"
#endif
Run Code Online (Sandbox Code Playgroud)
编译g++ -c foo.cpp工作正常:(g ++ v8.2.0)
foo.cpp:3:2: warning: #warning "hello, world" [-Wcpp]
#warning "hello, world"
^~~~~~~
Run Code Online (Sandbox Code Playgroud)
现在,如果我取代#define ID A用#define *,然后我得到:
foo.cpp:1:12: error: operator '*' has no left operand
#define ID *
^
foo.cpp:2:5: note: in expansion of macro ‘ID’
#if ID == A
^~
Run Code Online (Sandbox Code Playgroud)
有什么特别之处*?为什么它在#if表达式中失败?
您的帖子中有两点需要注意.首先,它不像你想象的那样有效.这也会产生警告
#define ID B
#if ID == A
#warning "hello, world"
#endif
Run Code Online (Sandbox Code Playgroud)
其原因是,在上下文中#if的预处理标记ID和A被当作宏和展开.由于A没有定义,它被"扩展"为0.所以ID通过扩展ID- > B- > 0.所以这里的情况也是如此.
这也解答了*导致错误的原因.它不能进一步扩展(由于不是有效的标识符),因此您得到比较* == 0,这是无稽之谈.
由于你的标题暗示你试图与字符常量进行比较,所以这样做的方法是定义ID扩展为字符常量的标记序列.
#define ID 'A'
#if ID == 'A'
Run Code Online (Sandbox Code Playgroud)
它应该按预期工作.一如既往#define ID '*'
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |