What are function pointers?
- A function has a physical location in the memory which is the entry point of the function. And this is the address used when a function is called. This address can be assigned to a pointer. Once a pointer points to a function, the function can be called through that pointer. Function pointers also allow functions to be passed as arguments to other functions. The address of a function is obtained by using the function’s name without any parenthesis or arguments.
- Consider the following example :
#include <iostream>
using namespace std;
void check(char *a, char *b, int (*cmp) (const char*, const*));
int numcmp(const char *a, const char *b);
int main()
{
char s1[80], s2[80];
gets (s1);
gets (s2);
if (isalpha(*s1))
check(s1, s2, strcmp);
else
check(s1, s2, numcmp);
return 0;
}
void check(char *a, char *b, int (*cmp) (const char*, const*))
{
cout <<”Testing for equality \n”;
if(!(*cmp)(a,b))
cout <<“Equal”;
else
cout <<“ Not Equal”;
}
int numcmp(const char *a, const char *b)
{
if(atoi(a) == atoi(b))
return 0;
else
return 1;
}
- In this function, if you enter a letter, strcmp() is passed to check() otherwise numcmp() is used.