Monday, January 11, 2010

Pointers to functions in C

I'm going to show a silly example to describe how to use pointers to functions. They are very usefull. Imagine that you are in a loop and want to execute a function when the index's are odd numbers and another function in even numbers.

#include 
#include

void (*fp)(int);
void fun1(int a);
void fun2(int a);


main () {
int i=0;
fp=&fun1;
for(i;i<5;i++) {
(*fp)(i);
}
}


void fun1(int a) {
printf("Even number: %d\n",a);
fp=fun2;
}

void fun2(int a) {
printf("Odd number: %d\n",a);
fp=fun1;
}


Output:
Even number: 0
Odd number: 1
Even number: 2
Odd number: 3
Even number: 4


In the main method we set the first function to use. Then when we call a function, each function changes the function address to the other function. This way, we can avoid and if condition inside the loop.

No comments: