C Function Pointer

Pointer to function in C

As we discussed in the previous chapter, a pointer can point to a function in C. However, the declaration of the pointer variable must be the same as the function. Consider the following example to make a pointer pointing to the function.

snippet
#include<stdio.h>
int addition ();
int main ()
{
	int result; 
	int (*ptr)();
	ptr = &addition;
	result = (*ptr)();
	printf("The sum is %d",result);
}
int addition()
{
	int a, b; 
	printf("Enter two numbers?");
	scanf("%d %d",&a,&b);
	return a+b;
}

Output

Output
Enter two numbers?10 15 The sum is 25

Pointer to Array of functions in C

To understand the concept of an array of functions, we must understand the array of function. Basically, an array of the function is an array which contains the addresses of functions. In other words, the pointer to an array of functions is a pointer pointing to an array which contains the pointers to the functions. Consider the following example.

snippet
#include<stdio.h>
int show();
int showadd(int);
int (*arr[3])();
int (*(*ptr)[3])();

int main ()
{
    int result1;
	arr[0] = show;
	arr[1] = showadd;
	ptr = &arr;
	result1 = (**ptr)();
	printf("printing the value returned by show : %d",result1);
	(*(*ptr+1))(result1);
}
int show()
{
	int a = 65;
	return a++;
}
int showadd(int b)
{
    printf("\nAdding 90 to the value returned by show: %d",b+90);
}
Output
printing the value returned by show : 65 Adding 90 to the value returned by show: 155
--------------------------------------------

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.

snippet
#include <stdio.h>
int main()
{
    printf("Address of main() function is %p",main);
    return 0;
}

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

snippet
return type (*ptr_name)(type1, type2…);

For example:

snippet
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.

snippet
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.

snippet
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.

Note
Note: Declaration of a function is necessary before assigning the address of a function to the function pointer.

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:

snippet
float func(int , int);      // Declaration of a function.

Calling an above function using a usual way is given below:

snippet
result = func(a , b);     // Calling a function using usual ways.

Calling a function using a function pointer is given below:

snippet
result = (*fp)( a , b);    // Calling a function using function pointer.

Or

snippet
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.

Let's understand the function pointer through an example.

snippet
#include <stdio.h>
int add(int,int);
int main()
{
   int a,b;
   int (*ip)(int,int);
   int result;
   printf("Enter the values of a and b : ");
   scanf("%d %d",&a,&b);
   ip=add;
   result=(*ip)(a,b);
   printf("Value after addition is : %d",result);
    return 0;
}
int add(int a,int b)
{
    int c=a+b;
    return c;
}

Output

C Function Pointer

Passing a function's address as an argument to other function

We can pass the function's address as an argument to other functions in the same way we send other arguments to the function.

Let's understand through an example.

snippet
include <stdio.h>
void func1(void (*ptr)());
void func2();
int main()
{
    func1(func2);
     return 0;
}
void func1(void (*ptr)())
{
    printf("Function1 is called");
    (*ptr)();
}
void func2()
{
    printf("\nFunction2 is called");
}

In the above code, we have created two functions, i.e., func1() and func2(). The func1() function contains the function pointer as an argument. In the main() method, the func1() method is called in which we pass the address of func2. When func1() function is called, 'ptr' contains the address of 'func2'. Inside the func1() function, we call the func2() function by dereferencing the pointer 'ptr' as it contains the address of func2.

Output

C Function Pointer

Array of Function Pointers

Function pointers are used in those applications where we do not know in advance which function will be called. In an array of function pointers, array takes the addresses of different functions, and the appropriate function will be called based on the index number.

Let's understand through an example.

snippet
#include <stdio.h>
float add(float,int);
float sub(float,int);
float mul(float,int);
float div(float,int);
int main()
{
    float x;              // variable declaration.
    int y;
    float (*fp[4]) (float,int);        // function pointer declaration.
    fp[0]=add;              // assigning addresses to the elements of an array of a function   pointer.
    fp[1]=sub;
    fp[2]=mul;
    fp[3]=div;
    printf("Enter the values of x and y :");
    scanf("%f %d",&x,&y);
  float r=(*fp[0]) (x,y);        // Calling add() function.
    printf("\nSum of two values is : %f",r);
     r=(*fp[1]) (x,y);             // Calling sub() function.
    printf("\nDifference of two values is : %f",r);
      r=(*fp[2]) (x,y);            // Calliung sub() function.
    printf("\nMultiplication of two values is : %f",r);
     r=(*fp[3]) (x,y);           // Calling div() function.
    printf("\nDivision of two values is : %f",r);
    return 0;
}

float add(float x,int y)
{
    float a=x+y;
    return a;
}
float sub(float x,int y)
{
    float a=x-y;
    return a;
}
float mul(float x,int y)
{
    float a=x*y;
    return a;
}
float div(float x,int y)
{
    float a=x/y;
    return a;
}

In the above code, we have created an array of function pointers that contain the addresses of four functions. After storing the addresses of functions in an array of function pointers, we call the functions using the function pointer.

Output

C Function Pointer
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +