C Function Pointer in C Language
Categories: C language
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.
#include <stdio.h>
int main()
{
printf("Address of main() function is %p",main);
return 0;
}
The above code prints the address of main() function.
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
return type (*ptr_name)(type1, type2…);
For example:
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.
float (*fp) (float);
In the above declaration, *fp is a pointer that points to a function that returns a float value and accepts a float value as an argument.
We can observe that the declaration of a function is similar to the declaration of a function pointer except that the pointer is preceded by a '*'. So, in the above declaration, fp is declared as a function rather than a pointer.
Till now, we have learnt how to declare the function pointer. Our next step is to assign the address of a function to the function pointer.
float (*fp) (int , int); // Declaration of a function pointer.
float func( int , int ); // Declaration of function.
fp = func; // Assigning address of func to the fp pointer.
In the above declaration, 'fp' pointer contains the address of the 'func' function.
Calling a function through a function pointer
We already know how to call a function in the usual way. Now, we will see how to call a function using a function pointer.
Suppose we declare a function as given below:
float func(int , int); // Declaration of a function.
Calling an above function using a usual way is given below:
result = func(a , b); // Calling a function using usual ways.
Calling a function using a function pointer is given below:
result = (*fp)( a , b); // Calling a function using function pointer.
Or
result = fp(a , b); // Calling a function using function pointer, and indirection operator can be removed.
The effect of calling a function by its name or function pointer is the same. If we are using the function pointer, we can omit the indirection operator as we did in the second case. Still, we use the indirection operator as it makes it clear to the user that we are using a function pointer.