Home > Software engineering >  Referring to a C function pointer with or without '&'?
Referring to a C function pointer with or without '&'?

Time:09-07

In C, a function pointer (evidently) can be referred to with or without the & operator. 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:

#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);
}

CodePudding user response:

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 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.

Rationale

A function identifier can implicitly convert to a pointer to a 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. The use of the '& (address-of)' operator will resolve this ambiguity.

From 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.)

  • Related