Monday, October 19, 2009

Pointers - Example 4

/*Function Pointers: Just like integer and character pointers but points to a function. They are declared as follows: <return-type> (*functionname) (arglist)
Assigning a function pointer: functionpointer = name-of-the-function
for eg, in the code below: fptr = findsum; and later fptr = finddiff;
The only catch is that the return-type and arglist of both functions must be the same(Note that findsum and finddiff have the same proto-type).
*/

#include <stdio.h>
void findsum(int *n1, int *n2);
void finddiff(int *n1, int *n2);


int main() {
int n1 = 5, n2 = 3;
void (*fptr) (int *n1, int *n2);
fptr = findsum;
(*fptr) (&n1,&n2); //fptr points to findsum
fptr = finddiff;
(*fptr) (&n1,&n2); //fptr points to finddiff
return 0;
}

void findsum(int *n1, int *n2) {
printf("Sum is %d\n", (*n1+*n2));
}

void finddiff(int *n1, int *n2) {
printf("Diff is %d\n", (*n1-*n2));
}

No comments:

Post a Comment