43. Explain about pointers to functions.
Answer:
Pointers to Functions
A pointer to a function is variable which points to the address of a function. If is possible to use a pointer to calla function and to even pass the function as an argument to another functions. In a program, memory is allocated for the function. The name assigned to function points of first byte of memory, with this it acts as the pointer constant. Pointers to function variables are defined similarly to that of other pointer type. For declaring the pointer to a function, the function pointer must be enclosed in parenthesis.
Syntax
function.return type (*pointer
name) (function argument list)
Here, the function return type indicates return type of the function, pointer name indicates pointer to a function or function pointer and argument list indicates arguments passed to the function.
Example
int (*f) (int, int);
In the above example ‘int’ is the return type of the function, f is the pointer to function (or) function pointer and (int, int) are the arguments of the function.
Here, the function pointer is enclosed in parenthesis because operators have higher priority over pointers in declaration. The remaining part is similar to that of a function prototype definition. The memory is allocated for the declared function,
Figure: Memory for Function
Here, f is the function pointer which stores the address of the function f.
Program
#include<iostream>
#include<conio.h>
using namespace std;
int sum (int num1, int num2)
{
return num1+num2;
}
int main()
{
int (*f) (int, int);
f=sum;
//Calling function using function
pointer
int result = f(10, 13);
cout<<“Result using function
pointer: "<<result;
return 0;
}
Output