C Function Pointer

As we know that we can create a pointer of any data type such as int, char, float, we can also create a pointer pointing to a function. The code of a function always resides in memory, which means that the function has some address. We can get the address of memory by using the function pointer.

Let's see a simple example.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     printf("Address of main() function is %p",main);  
  5.     return 0;  
  6. }  

The above code prints the address of main() function.

Output

C Function Pointer

In the above output, we observe that the main() function has some address. Therefore, we conclude that every function has some address.

Declaration of a function pointer

Till now, we have seen that the functions have addresses, so we can create pointers that can contain these addresses, and hence can point them.

Syntax of function pointer

  1. return type (*ptr_name)(type1, type2…);  

For example:

  1. int (*ip) (int);  

In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts an integer value as an argument.

Let's understand the function pointer through an example.

  1. #include <stdio.h>  
  2. int add(int,int);  
  3. int main()  
  4. {  
  5.    int a,b;  
  6.    int (*ip)(int,int);  
  7.    int result;  
  8.    printf("Enter the values of a and b : ");  
  9.    scanf("%d %d",&a,&b);  
  10.    ip=add;  
  11.    result=(*ip)(a,b);  
  12.    printf("Value after addition is : %d",result);  
  13.     return 0;  
  14. }  
  15. int add(int a,int b)  
  16. {  
  17.     int c=a+b;  
  18.     return c;  
  19. }  

Output

C Function Pointer