Friday, April 17, 2009

Pointer to Functions

I've seen pointers point to all the fundamental types and I've seen pointers point to the compound type known as array but I recently learned that pointers can also point to functions. To declare a pointer to a function that returns an integer and has an integer as its parameter you write

(int)(*pt)(int);

Say you have a function called square. The square function returns an integer and has an integer as its parameter.

int square(int x) { return x * x ; }

Now you want to assign the pointer to the function. Note: The address of a function is in the function name, therefore

pt = square; // is valid.

now if you want to call the function through the pointer, all you have to do is

(*pt)(2); // is 4

or simply

pt(2); // is 4 too

The pointer's ability to point to a function is useful when one wants to create a function that has other functions as its parameters. You would not want to create entire copies of the function, rather you'd want to refer to the function, therefore saving space and time.

No comments: