Arrays of Functions

A pointer to a function refers to the memory address of the function. Just like arrays, the name of a function is the starting address of the function’s code. Here’s a function prototype that recieves a pointer to a function as one of its parameters:

void update( employee [], int, void (*)() );

This indicates that “update” will recieve a function as an argument that is referenced by a pointer.

Suppose you have a couple of functions defined for manipulating some array of type employee: ComputeSalary, GiveRaise, Demote, Promote, etc. This would be the ideal call to the update function, assuming that the array of employees name is roll and the employee you wish to modify is indexed by being the fourth element of this array and you wish to ComputerSalary:

update( roll, 4, ComputeSalary );

If you wanted to Demote:

update( roll, 4, Demote );

Now, further suppose that you’ve got three functions: A, B, and C. Each returns void and takes one integer argument. To declare an array of pointers to these three functions:

void (*AoP[3])(int) = {A, B, C};

To call the nth element (or function) of AoP with argument Z:

(*AoP[n])(Z);
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: