Mykie
Mykie

Reputation: 173

Cast a function pointer

Suppose I have a function

void myFun(int*) 
In C++ what exactly does the following mean


  ( void(*)(void*) )&myFun

Is it a pointer to a function that takes a (void*) as an argument and returns a void? Is this type of cast permitted?

Upvotes: 2

Views: 8172

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490653

As it stands, I'm pretty sure it's just not allowed.

If you remove the parens around the initial void to get:

void (*)(void *)

...then yes, it's a pointer to a function returning void and taking a pointer to void as its only argument. To cast to that type, you need to enclose the entire name of the type in parentheses, so you'd get: (void (*)(void *)), which you'd follow by the value being cast, to get:

(void (*)(void *))&myFun;

At least if memory serves, yes, this is allowed, though dereferencing the pointer (i.e., attempting to call the function it points at) via the result may give undefined behavior. In particular, when/if you call the function, it's expecting a pointer to int, and will (presumably) use whatever it points at as an int. If, however, what it points at isn't properly aligned to be used as an int, it's not likely to work as expected.

Upvotes: 6

ecatmur
ecatmur

Reputation: 157484

The cast is permitted, by 5.2.10 (6):

A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined. Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

This is equivalent to C 6.3.2.3 (8):

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

In practice, calling through a function pointer with different but compatible argument types (especially pointer types) usually succeeds, and has the effect of a C-style cast on the arguments. This is by no means guaranteed, however; https://stackoverflow.com/a/189126/567292 discusses a case where gcc decided to make such undefined function pointer cast calls abort.

Upvotes: 3

Related Questions