foo.cpp
:
#define ID A
#if ID == A
#warning "hello, world"
#endif
使用g++ -c foo.cpp
进行编译可以正常工作:(g ++ v8.2.0)
foo.cpp:3:2: warning: #warning "hello, world" [-Wcpp]
#warning "hello, world"
^~~~~~~
现在,如果我将#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
^~
*
有什么特别之处?为什么在#if
表达式中失败?
答案 0 :(得分:5)
您的帖子中有两点值得注意。首先,它无法按照您的想法工作。这将produce the warning too
#define ID B
#if ID == A
#warning "hello, world"
#endif
原因是,在#if
的上下文中,预处理令牌ID
和A
被用作宏并被扩展。由于未定义A
,因此将其“扩展”为0。通过扩展ID
-> ID
-> B
,0
也是如此。因此,这里的条件也是如此。
这也回答了*
导致错误的原因。它不能进一步扩展(由于不是有效的标识符),因此您将获得比较* == 0
,这是毫无意义的。
由于标题暗示您试图与字符常量进行比较,因此,可以通过定义ID
来将扩展为字符常量的标记序列。
#define ID 'A'
#if ID == 'A'
现在应该可以正常工作了。 #define ID '*'
答案 1 :(得分:1)