This blog is under construction

Tuesday, 31 December 2013

How to call functions using function pointers?

What is function pointer?
Every function has an address.  We can assign the address of functions to pointers.  Then those pointers are called pointers to functions.  Pointers to function is also called as function pointers

Let us see how to call functions using function pointer.  Below is an example function pointer

int (*func)(int, int);
Here, func is a pointer to a function that takes two integer arguments and returns an integer

Consider the following example,
int add(int a, int b) {
         return (a + b);
}

int main() {
          int (*func) (int, int);
          func = add;  //assigning address of function add()
          (*func)(10, 20);  // calls the add function
          return 0;
}

Here,
"func = add" is equivalent to "func = &add"(& is optional)
"(*func)(10, 20)" is equivalent to "func(10, 20)" (* is optional)

Let us write an example C program that calls a function using function pointer.

 
  #include <stdio.h>
  int add(int a, int b) {
        return (a + b);
  }

  int main() {
        int res;
        int (*func)(int, int);
        func = &add;  // assign address of the function add()
        res = func(10, 20);  // calling add()
        printf("Sum of 10 and 20 is %d\n", res);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Sum of 10 and 20 is 30



No comments:

Post a Comment