This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 7.11.3 - A conversion from function type to pointer-to-function type shall only occur in appropriate contexts
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
A conversion to pointer to function is appropriate when it occurs:
- Through a
static_cast; or
- In an assignment to an object with pointer-to-function type.
Rationale
The use of a function pointer in Boolean contexts may result in a well-formed program that 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 evaluates to
nullptr, or that a call to the function f should be made but the call operator has been unintentionally omitted. The use of
the & (address-of) operator or an explicit conversion with a static_cast to a function pointer removes this
ambiguity.
Using a function as an operand in an arithmetic expression will trigger pointer decay.
Example
extern int * f();
if ( f == nullptr ) // Non-compliant
{
}
if ( &f != nullptr ) // Compliant - no conversion
{
(f)(); // Compliant - no conversion
}
std::cout << std::boolalpha // Compliant - assignment to pointer-to-function type
<< f; // Non-compliant - assignment is not to
// pointer-to-function type
auto x = +f; // Non-compliant
void f1( double );
void f1( uint32_t );
auto selected = static_cast< void(*)( uint32_t ) >( f1 ); // Compliant
auto lam = [](){};
void ( *p )() = lam; // Compliant
auto x = +lam; // Non-compliant
if ( lam ) // Non-compliant
{
}
Copyright The MISRA Consortium Limited © 2023