调用函数而不是C中的宏 [英] Invoke function instead of macro in C
问题描述
我的问题是:如果您有一个宏和一个具有相同名称的函数,那么只会调用该宏,对吗?如果我想调用函数而不是宏怎么办?
My question is: If you have a macro and a function with the same name, only the macro would be invoked, right? What if I want to invoke the function instead of the macro?
推荐答案
如果您有一个名为foo
的函数和类似函数的宏,并且想要调用函数版本,则可以执行以下操作:
If you have a function and a function-like macro both named foo
and want to invoke the function version, you can do:
(foo)(args)
之所以可行,是因为类似函数的宏名称必须后跟一个带括号的参数列表,以进行替换.
This works because function-like macro names must be followed by a parenthesized argument list for substitution to occur.
ISO C99标准的7.1.4/1部分对此进行了提及:
This is mentioned in section 7.1.4/1 of the ISO C99 standard:
标头中声明的任何函数都可以另外实现为标头中定义的类似函数的宏,因此,如果在包含标头时显式声明了库函数,则可以使用以下所示的一种技术来确保声明不受此类宏的影响.通过在函数名称中用括号括起来,可以在本地抑制函数的任何宏定义,因为该名称之后不带有表示宏函数名称扩展的左括号.出于相同的语法原因,即使将库函数也定义为宏,也可以采用该函数的地址.使用
#undef
删除任何宏定义也将确保引用实际函数.
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.
但是,如果您需要执行此操作,则可能应在代码中添加注释以对其进行解释,因为它看起来有点怪异且不常见.如果可行,从长远来看,重命名该功能以避免名称冲突可能更可维护.
If you need to do this, though, you probably should add comments to your code explaining it since it looks a little weird and isn't common practice. If feasible, renaming the function to avoid the name collision might be more maintainable in the long run.
这篇关于调用函数而不是C中的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!