Why is this an issue?
Using a "bald" function name is likely a bug. Rather than testing the return value of a function with a void
parameter list, it
implicitly retrieves the address of that function in memory. If that’s truly what’s intended, then it should be made explicit with the use of the
&
(address-of) operator. If it’s not, then a parameter list (even an empty one) should be added after the function name.
Noncompliant code example
int func(void) {
// ...
}
void f2(int a, int b) {
// ...
if (func) { // Noncompliant: tests that the memory address of func() is non-null
//...
}
// ...
}
Compliant solution
int func(void) {
// ...
}
void f2(int a, int b) {
// ...
if (func()) { // Compliant: tests that the return value of func() > 0
//...
}
// ...
}
Exceptions
Callback functions are a common occurrence and are usually not passed with a preceding &
. However, there is little ambiguity, so
this rule ignores function identifiers when used as a parameter of a function call.
void foo() {
// ...
}
registerEvent(AnEvent, foo); // Compliant by exception
Resources
- MISRA C:2004, 16.9 - A function identifier shall only be used with either a preceding &, or with a parenthesized parameter list, which may
be empty.
- MISRA C++:2008, 8-4-4 - A function identifier shall only be used to call the function or it shall be preceded by &.