POINTERS TO FUNCTIONS
A function like a variable, has an address location in the memory. It is therefore, possible to declare a pointer to a function, which can then be used as an argument in another function. A pointer to a function is declared as follows:
type ( * fp) ( ) ;
This tells the compiler that fp is a pointer to a function which returns type value.
We can make a function pointer to point to a specific function by simply assigning the name of the function to the pointer.
For example
double (*P1)( ), mul ( ) ;
P1 = mul ;
declare P1 as a pointer to a function and mul as a function and then make P1 to point to the function mul. To call the function mul, we may now use the pointer P1 with the list of parameters.
That is,
(*P1) (x,y)
is equivalent to mul ( x,y )
FUNCTIONS RETURNING POINTERS
The way functions return an int, a float, a double or any other data type, it can even return a pointer. However, to make a function return a pointer it has to be explicitly mentioned in the calling function as well as in the function declaration.
The following program illustrates this
main ( )
{
int * P ;
int * fun ( ) ;
P = fun ;
printf ( “\n % Id”, P ) ;
}
int * fun ( )
{
int i = 20;
return (& i) ;
}
In this program, function fun( ) is declared as pointer returning function can return the address of integer type value and in the body of the function fun ( ) we are returning the address of integer type variable i into P which is also integer type pointer.
Showing posts with label Pointers to Functions. Show all posts
Showing posts with label Pointers to Functions. Show all posts
Sunday, November 16, 2008
Subscribe to:
Posts (Atom)