Sunday, 3 February 2019

Function pointer in C

Function pointer in C


What is the function pointer in C?

Function pointer in C is similar to a normal pointer. The difference between function pointer in C and in normal pointers is that normal pointers point to the address of data but function pointers point to the address of the function. Function pointer in C is also known as the pointer to function.


TO LEARN ABOUT WHAT IS POINTERS IN C



Declaration of function pointer in C

Declaration of function pointer in C similar to function. The only difference is that whenever we declared function pointer we use * before declaration name and enclosed in parenthesis.

Syntax

return type     (*identity   (argument-list)


For example

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

In the above expression, p is a function pointer taking two arguments (int, int) and returns an integer. In the above expression, brackets play a very important role, if we removed brackets then it becomes int *p (int, int), which is the declaration of a function with two integer pointer as arguments and returns integer pointer.

Initialization of function pointer in C

Function pointer in C is initialized similarly to the initialization of normal pointers in C. 

Initialization of normal pointers in C

#include <stdio.h>
int main ()
{
int *p // declaration of pointer p
int a =34; // declaration and initialization of variable a
p = &a; // initialization of pointer p
printf ("value =%d\n", *p);
return 0;
}

Initialization of function pointers in C

#include <stdio.h>
#include <stdlib.h>

//function used to add two numbers
int sub(int a, int b)
{
  int c;
  c=a-b;
  return c;
}


int main()
{
 int q= 0;
 //Declaration of function pointer p
 int (*p)(int,int) = NULL;
 //initialization of the function pointer
 p = sub;
 //Calling the function using function pointer
 q = (*p)(50,20);
 printf("\n\n Subtraction of two number = %d\n\n",q);
 return 0;
}


Output
Subtraction of two number = 30








No comments:

Post a Comment