Arrays of Functions

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:

See also  How to Avoid Money Transfer Scams  

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist