Example Code:
Here is a example code of function pointer cast.
void MyFunc() {
cout << "hello" << endl;
}
typedef void (*func) ();
int main() {
func a = static_cast<func>(&MyFunc);
a();
return 0;
}
The instance of func
we declared as a
is a function pointer that points to the function MyFunc.
We call a();
as the same as we call the function MyFunc();
.
As the draft of C99 standard described:
The behavior is undefined in the following circumstances:
- A pointer is used to call a function whose type is not compatible with the pointed-to type (6.3.2.3).
The function pointer that we declared must be compatible with the function type we will point to. Otherwise it will be undefined behavior.
Other
More detail about the function pointer cast.
http://stackoverflow.com/a/559671