20130421

How to use callback function pointer in cpp/C/C++

Program for callback /function pointer in CPP/C/C++

What is function pointers?As we know a pointer is a special variable that folds the address of another variable.
Function pointer is also  a pointer that hold the address of a function.
Int array[10]; // here array is a constant pointer to a 10 element array. That is constant pointer to first element of array.
Can we declare a non-constant pointer to a function? Yes we can .
Int (*funcPtr)();//funcPtr is a pointer to a function that takes no arguments and returns an integers.//parenthesis is must here as we are not assigning the return type.
Int (*funcPtr)(int,int);//funcPtr is a pointer to a function that takes two arguments and returns an integers.
Callback function-callback function is reference to a piece of executable code that is past as arguments to another code.
  • This allows a lower level layer code to call a function defined in higher level layer.
  • Function pointer are used in many situation like if you are writing a code for sorting an array but instead of hard coding the code of comparison of elements to sort we can provide a way to the user to defined how a particular part of the code will be performed such as array is sorted in ascending or descending order.
Simple example of a function:
#include<stdio.h>
int func(int,int);
int main()
{
int sum;
sum=func(1,2);
printf("\sum=%d\n",sum);
return 0;
}
int func(int a, int b)
{
return a+b;
}
Callback function : example of a function pointer in cpp/C/C++:
//Program for callback function Pointer
#include<stdio.h>
int func(int,int);
int main()
{
//decalring a func ptr taking 2 args and returning a int
int(*funcPtr)(int, int);
int sum;
funcPtr=func;//assiging a function addr to ptr
//calling function through explicit dereference
sum=(*funcPtr)(1,2);
printf("\nSum=%d\n",sum);

//calling function through implicit dereference
sum=funcPtr(1,2);
printf("\nSum=%d\n",sum);
return 0;
}
int func(int a, int b)
{
return a+b;
}

No comments:

Post a Comment