简体   繁体   English

引用带有或不带有“&”的 C function 指针?

[英]Referring to a C function pointer with or without '&'?

In C, a function pointer (evidently) can be referred to with or without the & operator.在 C 中,可以使用或不使用&运算符来引用 function 指针(显然)。 Is there a stylistic reason to choose one over the other?是否有风格上的理由来选择一个而不是另一个?

The following code compiles and runs in gcc x86-64 12.2 -Wall without any warnings:以下代码在 gcc x86-64 12.2 -Wall 中编译并运行,没有任何警告:

#include <stdio.h>

int cb1(void) { return 1; }

int cb2(void) { return 2; }

void do_cb(int (*cb)(void)) { printf("%d\n", cb()); }

int main(void) {
    do_cb(cb1);
    do_cb(&cb2);
}

Is there a reason to choose one over the other?有理由选择一个而不是另一个吗?

& is demanded in front of function identifiers by MISRA 2004. I like it, I think it looks nice and explicitly conveys the intent. &被 MISRA 2004 要求在 function 标识符前面。我喜欢它,我认为它看起来不错并且明确地传达了意图。

MISRA C Rule 16.9 (required): A function identifier shall only be used with either a preceding '&', or with a parenthesised parameter list, which may be empty. MISRA C 规则 16.9(必需):function 标识符只能与前面的“&”或带括号的参数列表一起使用,该列表可能为空。

Rationale基本原理

A function identifier can implicitly convert to a pointer to a function. function 标识符可以隐式转换为指向 function 的指针。 In certain contexts this may result in a well-formed program, but which is contrary to developer expectations.在某些情况下,这可能会导致程序结构良好,但这与开发人员的期望相反。 For example, if the developer writes例如,如果开发人员写

if ( f )

then it is not clear whether the intent is to test if the address of the function is NULL or if a call to the function 'f()' should be made and the brackets have been unintentionally omitted.那么不清楚是否意图测试 function 的地址是否为 NULL 或者是否调用 function 应该无意中省略了括号并且应该省略括号() The use of the '& (address-of)' operator will resolve this ambiguity. '& (address-of)' 运算符的使用将解决这种歧义。

From https://analyst.phyzdev.net/documentation/help/reference/misra.func.addr.htm , https://rules.sonarsource.com/cpp/RSPEC-936 .来自https://analyst.phyzdev.net/documentation/help/reference/misra.func.addr.htm,https ://rules.sonarsource.com/cpp/RSPEC-936

(I think the rule was removed in MISRA 2012. I wonder what is the rationale.) (我认为 MISRA 2012 中删除了该规则。我想知道原因是什么。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM