c - 在 C 中调用函数而不是宏

标签 c macros

我的问题是:如果你有一个宏和一个同名的函数,那么只会调用宏,对吗?如果我想调用函数而不是宏怎么办?

最佳答案

如果你有一个函数和一个类似函数的宏,它们都命名为 foo 并且想要调用函数版本,你可以这样做:

(foo)(args)

这是有效的,因为类似函数的宏名称必须后跟带括号的参数列表才能进行替换。

这在 ISO C99 标准的第 7.1.4/1 节中提到:

Any function declared in a header may be additionally implemented as a function-like macro defined in the header, so if a library function is declared explicitly when its header is included, one of the techniques shown below can be used to ensure the declaration is not affected by such a macro. 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. The use of #undef to remove any macro definition will also ensure that an actual function is referred to.

但是,如果您需要这样做,您可能应该在代码中添加注释来解释它,因为它看起来有点奇怪并且不常见。如果可行,重命名函数以避免名称冲突从长远来看可能更易于维护。

关于c - 在 C 中调用函数而不是宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15654070/

相关文章:

c - ## 宏预处理器的使用

arrays - 分段故障(核心已转储)需要建议

c - 按位移位生成 C 中所有可能的排列

c - c崩溃有多严重?

c - 给定某个整数 N,有多少个基数 b 使得 N 的基数 b 表示以 1 开头?

c - 为什么即使我定义了 _GNU_SOURCE 也无法访问 uname 结构体的域名成员

c - 如何测试结构释放

c - 使用#define 替换连续的字符串

c - 像宏这样的功能是什么意思?

c - 宏扩展和字符串化 : How to get the macro name (not its value) stringified using another macro?