function+pointers

Function pointers in C have an awfully terrifying appearance, but aren't so difficult once you get used to them.

A function pointer is a pointer to a function rather than an object in memory. We can get the address of a function the same way as for a variable:

code format="c" double ratio(int x, int y) { return (double) x / y; }

int main(void) { ... my_func = &ratio; } code

The declaration is a little more cumbersome. For the above definition of "ratio", which accepts two integers and returns a double, it looks like:

code format="c" double (*my_func)(int, int) = NULL; my_func = &ratio; code

To call a function pointer, dereference it and give it the appropriate arguments:

code format="c" result = (*my_func)(i, j); code

Putting it all together, an example program looks like this:

code format="c"
 * 1) include 

double ratio(int x, int y) { return (double) x / y; }

double squared_sum(int x, int y) { return (double) x * x / y / y; }

void test_binary(double (*func)(int, int), char *name) { int i, j; double result; printf("Testing the output of function \"%s\":\n", name); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { result = (*func)(i, j); printf("\t(%d, %d) -> %f\n", i, j, result); } } }

int main(void) {

double (*my_func)(int, int) = NULL;

my_func = &ratio; test_binary(my_func, "ratio");

test_binary(&squared_sum, "squared sum");

return 0; } code