我定义了两次宏如下:
#define a 2
#define a 3
我认为代码中出现的任何 a
都会被替换为 2
,而当遇到 #define a 3
时,没有代码中有更多的 a
可用 3
替换,因此 2
将优先。
但是我执行的时候a
被3代替了,为什么?
最佳答案
如果你像这样定义一个宏两次,编译器至少应该给你警告,如果不是错误的话。这是一个错误。
§6.10.3/2 : An identifier currently defined as an object-like macro shall not be redefined by another
#define
preprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical.
您可以通过显式删除以前的定义来重新定义宏:
#define a 2
/* In this part of the code, a will be replaced with 2 */
...
#undef a
#define a 3
/* From here on, a will be replaced with 3 */
...
宏替换在文件被读取时发生,使用文件中此时处于事件状态的宏定义,除了在(大多数)预处理指令内。
§6.10/7: The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated.
§6.10.3.5/1: A macro definition lasts (independent of block structure) until a corresponding
#undef
directive is encountered or (if none is encountered) until the end of the preprocessing translation unit.
关于c - 当 C 预处理器宏被定义两次时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32431033/