C Function Pointer

We declare a pointer to integer, pointer to character or pointer to array. Similarly we can declare a pointer to function or a function pointer. Same as like variables, functions also have some address in memory.

C Function Pointer

A function pointer is a pointer that contains the address of a function. It can be declared in following way. You must follow the same syntax for declaration otherwise you will get an error.

Syntax
return_type (* pointer_name) (argument_list);

Example
int (*p) (int, int);

In above example we are declaring a pointer to function or a function pointer that will contain the address of a function with return type integer and having two integer arguments.

The above function pointer p can be assigned address of a function and can call that function in following way. Lets assume the function with name fun1().

//storing address of function in the function pointer p
p = fun1; //first way
p = &fun1 //second way

//calling the function using function pointer p
int c = (*p)(2,3); //first way
int c = p(2,3); //second way

As you can see in above example that function pointer can be assigned address and can call a function in two ways. You can use any one of them.

Lets make one program that will calculate addition of two numbers using the concept of function pointer in C.

#include<stdio.h>

int add(int a,int b)
{
 return a+b;
}

void main()
{
 int (*p)(int,int);
 
 p=&add;
 printf("Sum=%dn",(*p)(5,3));  

}

Output

C Function Pointer - Pointer to Funtion

Explanation
1. Firstly I have made a function add() that will take two integer arguments, calculate their addition and return the result.

2. Now in the main() function I am declaring a function pointer p and then storing the address of function add(). This can be done without using the address of operator i.e. &.

3. Finally I am calling the function using the function pointer and then displaying the result. As I have already mentioned above that the calling can also be done in two ways. So here we can call the function by simply writing p(5,3).

Below I have added a video that will help you in understanding the concept of function pointer or pointer to function in C.

C function pointer is an advance topic of pointer and a little bit difficult too. If you have any kind of queries then please mention it in comments.

1 thought on “C Function Pointer”

  1. Shankar Sivasubramaniyan

    //storing address of function in the function pointer p
    p = fun1; //first way
    p = &fun1 //second way

    but in the next example, it was stored like given below

    p=&add;// is this is the third way of storing?

Leave a Comment

Your email address will not be published. Required fields are marked *