c - 类似函数的宏和变量

标签 c c-preprocessor

出于某些难以理解的原因,在我的代码中我有类似的东西:

#define pippo(x) printf("%d",x)
...
... many lines down in the code
...
int pippo = 0;

相同的标识符 pippo 已用于类似函数的宏和变量名!除了这可能会引起可怜的维护者的困惑之外,我想知道这是否符合标准。

C99 和 C11(在 6.10.3.)都说:

10 [...] Each subsequent instance of the function-like macro name followed by a ( as the next preprocessing token introduces the sequence of preprocessing tokens that is replaced by the replacement list in the definition [...]

他们没有说如果类似函数的宏名称后跟'('会发生什么,我担心某些编译器可能会认为这是一个错误(或者可能只是发出警告)。

我是不是太担心了?

最佳答案

没有被 ( 跟随的类函数宏名称的实例不会被替换。

这样使用名称并不违反 C 标准中的约束。该标准甚至给出了使用此行为的示例。 C 2018 7.1.4 1,讨论标准库函数及其作为类函数宏的潜在实现(除了作为函数的定义),说:

… Any macro definition of a function can be suppressed locally by enclosing the name of the function in parentheses, because the name is then not followed by the left parenthesis that indicates expansion of a macro function name. For the same syntactic reason, it is permitted to take the address of a library function even if it is also defined as a macro…

编译器可能会发出警告(尽管当宏名称是上面 C 标准建议使用的库函数时,它可能希望抑制此警告),但 GCC 9.2 和 Clang 11.0.0 都不会,即使启用所有警告。

关于c - 类似函数的宏和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60379019/

相关文章:

c - 传入指向整数指针的指针时的斐波那契数列

c - 有没有办法将进程锁定到 CPU?

c - #including 标准库是如何工作的?

c - 调用对象 ‘x2’ 的宏错误不是函数

C编程文本文件不读取整行

c - 内核源码 3.10.0-229.11.1.el7.x86_64 编译失败

c++ - 里面的const变量是什么?

c - IAR编译器警告: "macro does not create a valid token"

C 预处理器指令运算符##

C++ 函数调用标识符