Using Pointers to Functions
In Objective-C, function names are actually pointers. You can pass function names to other functions, and in the receiving function, you can call the passed function name if you treat it as a pointer.
For example, you can pass function names to this function, named caller_function(), and it will call the passed function:
void caller_function(void (*pointer_to_ function)(void)) { (*pointer_to_function)(); }
To call a function pointer:
- Create a new program named functionpointers.m.
- In functionpointers.m, enter the code shown in Listing 4.19.
This code sets up a function named printem() and passes its name to caller_function().
- Add the code to implement caller_function(), which will call the function pointer you pass to it (Listing 4.20).
- Save functionpointers.m.
- Run the functionpointers.m program.
You should see the following:
Hello there
Listing 4.20. The functionpointers.m program.
#include <stdio.h> void printem(void); void caller_function(void (*pointer_to_ function)(void)); int main() { caller_function(printem); return 0; } void printem(void) { printf("Hello there"); } void caller_function(void (*pointer_to_ function)(void)) { (*pointer_to_function)(); }