我展示了一些我确实理解的代码。
以下代码是示例代码。
static void (_func)(int p);
int main()
{
....
_func(3);
....
}
static void (_func)(int p)
{
....
}
一般来说,我知道用括号括起来的函数与'*'一起用于函数指针作为(*_func),但上面的代码为什么在函数声明时用括号括起函数?
有什么理由使用这种方法吗?
我展示了一些我确实理解的代码。
以下代码是示例代码。
static void (_func)(int p);
int main()
{
....
_func(3);
....
}
static void (_func)(int p)
{
....
}
一般来说,我知道用括号括起来的函数与'*'一起用于函数指针作为(*_func),但上面的代码为什么在函数声明时用括号括起函数?
有什么理由使用这种方法吗?
Putting parens around a function name will prevent it from being 'overridden' by a function-like macro with the same name.
For example, sometimes a function might be implemented as a macro but it might also need to be implemented as an actual function (one reason might be so that a pointer to it can be obtained). The implementer of this API might put the declaration of the function name and the actual function implementation with the name wrapped in parens so that there's no conflict with the macro name.
Then the user of the API can decide that if for whatever reason they want to use the actual function instead of the macro, they can #undef _func
or use the function name wrapped in parens to avoid using the macro.
As mentioned in C99 7.1.4 "Use of library functions":
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.