Tuesday, February 9, 2010

This Monday, we are learning " pointer to function".

......

int main(){
int (*fptr[3])(int, int){add, prnHA, sub};
int a = 10;
int b = 20;
int c;
int i;
for(i=0;i<3;i++){
c = (*fptr[i])(a, b);
printf("%d\n", c);
}
return 0;
}

......

To my understanding, (*fptr[3]) is an array of variables which are pointers to functions, as long as the functions have the same signature as defined.
ex. ( int (*fptr)(int, int)) --
refers to any function which receives two integer as parameters and then return one integer.

In the example listed above, with one loop, we can call three different functions, add, prnHA and sub.
It is very cool!

No comments:

Post a Comment