c - 当 C 预处理器宏被定义两次时会发生什么?

标签 c macros c-preprocessor

我定义了两次宏如下:

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

相关文章:

c++ - 有没有办法断言当前命名空间?

c - IP 头按位定义解释需要

iphone - 试图使代码可读

c - 在不知道文件大小且数据类型顺序不一致的情况下如何从文件中读取数据

c - 用C语言将整个程序写入一个文件

c - MPI_Scatter 使用 C 和动态分配内存

C - 预处理器多个宏

c++ - 编译时动态函数调用

c++ - C++ 宏中的语句

c - 堆栈实现为数组,在 C 中默认第一个值为 0