为什么用括号括住函数? [英] Why surround the function with parentheses?

查看:156
本文介绍了为什么用括号括住函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我展示了一些我确实理解的代码.

I shown some code that i did understand.

以下代码是示例代码.

static void (_func)(int p);

int main()
{
....
    _func(3);
....
}

static void (_func)(int p)
{
 ....
}

通常,我知道用括号括起来的函数与(* _func)一起用'*'表示,但是在上面的代码中,为什么在函数声明时用括号将函数括起来?

Generally I know that function surrounded with parentheses is used with '*' for function pointer as (*_func), but above code why did surround the function with parentheses at declaration of function?

有什么理由要使用此方法吗?

Is there some reason to use this method ?

推荐答案

在函数名称周围添加括号将防止其被具有相同名称的类似函数的宏覆盖".

Putting parens around a function name will prevent it from being 'overridden' by a function-like macro with the same name.

例如,有时一个函数可能被实现为宏,但可能还需要将其实现为实际函数(一个原因可能是可以获取指向它的指针).该API的实现者可能会将函数名称的声明和实际的函数实现的名称包装在括号中,以便与宏名称没有冲突.

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.

然后,API的用户可以决定,如果出于某种原因,他们想使用实际的函数而不是宏,可以使用#undef _func或使用包裹在括号中的函数名来避免使用宏.

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.

如C99 7.1.4库函数的使用"所述:

As mentioned in C99 7.1.4 "Use of library functions":

标头中声明的任何函数都可以另外实现为 标头中定义的类似函数的宏,因此如果库函数是 在包含其标头时进行显式声明,这是一种技术 下面显示的内容可用于确保声明不受以下内容的影响 这样的宏.可以禁止函数的任何宏定义 在本地将函数名称括在括号中,因为 然后,该名称后不跟左括号,该左括号表示 宏功能名称的扩展.出于相同的语法原因,它 允许使用库函数的地址,即使它是 也定义为宏.使用#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.

这篇关于为什么用括号括住函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆