1 2 3 4 5 6 7 8 9

We can now invoke (call) this function via the pointer

value = (*fptr) ( 64, "Industrial Internship wins" );

But what are they really good for?

1. Passing a function as a parameter

By this means different operations can be done with the same piece of code

2. To select a function to call at run-time, so avoiding ugly (or impractical) switch statement.

For example, we want to read a key press and call a different action (function) depending on the key selected. For this we define an array of function pointers as follows:

int (*RespondToKeypress[256])();

RespondToKeypress['\t'] = tab_handler;

for ( i = 'a'; i <= 'z'; i++)
RespondToKeypress[i] = alpha_handler;

So now when some key c is pressed we invoke

RespondToKeypress[c](c);

and the job is done

4 February, 1998

3

Copyright University of Alberta