Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 4. Creating Functions > Using Pointers to Functions

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:

1.
Create a new program named functionpointers.m.

2.
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().

3.
Add the code to implement caller_function(), which will call the function pointer you pass to it (Listing 4.20).

4.
Save functionpointers.m.

5.
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)();
					}

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint