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++ - 为什么 isdigit() 如果为真则返回 2048?

c - 如何只读取最后 3 位数字?

c - 将所有包含文件放在一个头文件中是个好主意吗?

c++ - 在 C 中迭代 C++ 容器

c - 这个表达式是什么意思 "val&=val-1"

c - 这段 C 代码是如何工作的?

c - Tabular Recta 表未正确生成

c - 用 C 语言实现 Mandelbrot 缩放

c - 如何摆脱警告: deprecated conversion from string constant to char*