Search code examples
c++function-pointersundefined-behaviorreinterpret-cast

converting to function pointer from pointer to function with same signature, except additional qualification of parameter


void ( * pFunc_pcInt ) ( int const * ) = nullptr ; 
void ( * pFunc_pInt ) ( int * ) = reinterpret_cast< void ( * ) ( int * ) >( pFunc_pcInt ) ;

Does such conversion lead to undefined behavior.?


Solution

  • As from the standard (working draft, emphasis mine):

    A function pointer can be explicitly converted to a function pointer of a different type. [ Note: The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined.  — end note ] [...]

    And, of course, void(int const *) and void(int *) are different types.

    Something similar comes from one of the most known online reference (emphasis mine):

    Any pointer to function can be converted to a pointer to a different function type. Calling the function through a pointer to a different function type is undefined, but converting such pointer back to pointer to the original function type yields the pointer to the original function.

    In your specific case it doesn't matter that much, for you are assigning nullptr to the function pointer. Invoking it would lead to an error in any case.
    That being said, if you had assigned a valid function pointer to pFunc_pcInt, invoking it through the converted pointer pFunc_pInt would have been an UB.