c - C 中的多个宏

标签 c

#define a 10
#define a 20
{

    printf("%d",a);
}

为什么答案是 20 而不是 10? 由于/* #define a 10 */是第一个宏,所以不是应该用它来代替 'a' 吗?

最佳答案

你的问题的前提(应该使用第一个定义)是错误的。

您的编译器已决定使用第二个定义。它真的可以做任何它想做的事,因为你的程序格式不正确/损坏/错误:

[C99: 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. [..]

这里,在 the documentation ,我们看到 GCC 的非标准行为被明确定义:

If a macro is redefined with a definition that is not effectively the same as the old one, the preprocessor issues a warning and changes the macro to use the new definition. If the new definition is effectively the same, the redefinition is silently ignored. This allows, for instance, two different headers to define a common macro. The preprocessor will only complain if the definitions do not match.

简而言之:不要这样做。

关于c - C 中的多个宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42695880/

相关文章:

c - 按行与按列访问矩阵元素

c - 调整 Makefile 以进行交叉编译

c - 使用 glibc 依赖项从 chroot 动态加载库

c - memcpy 给了我奇怪的结构结果

c++ - C/C++ 中的领域特定语言,这是 Kosher 吗?

c - 优化磁盘 IO

c - 为什么我的随机数生成器仅生成随机数?

c - 为什么这个CPU运行速度更快?

c - 用不同的指针重新分配重叠指针

c - UDP客户端未收到消息