Wednesday, June 25, 2008

Pointer to functions - Simplified

Here is the code


1 #include < iostream >
2
3 using namespace std;
4
5 int add(int a, int b) {
6 return a+b;
7 }
8
9 int sub(int a, int b) {
10 return a-b;
11 }
12
13 // typdef pointer to a function
14 typedef int (*fpp)(int, int);
15
16 // Array of pointers to function
17 fpp fp[2];
18
19 // Function returning a pointer to a function
20 int (* getfp(int i) ) (int, int) {
21 if(i==1) return & add;
22 else return & sub;
23 }
24
25 // Pointer to a function returning a pointer to a function
26 int (* (*fgetfp)(int)) (int, int);
27
28 int main() {
29
30 fgetfp = &getfp;
31
32 fp[0] = (*fgetfp)(1); // same as fgetfp(x)
33 cout<<"10 + 20 = "<< fp[0](10,20)<< endl;
34
35 fp[1] = fgetfp(2);
36 cout<<"10 - 20 = "<< fp[1](10,20)<< endl;
37 return 0;
38 }
39

2 comments:

anonymousT said...

gimme some application of function pointers and "pointer to a fuction returning function pointers!"

Reemus Kumar said...

Here are some of the applications of Function Pointers. I think you know what these syscalls used for:

Function Pointer
++++++++++++++++
int atexit(void (*function)(void));

Function Returning Function Pointer
+++++++++++++++++++++++++++++++++++
void(*signal (int sig, void(*func)(int)))(int);