Pointers to Functions

A function even though not a variable still has a physical address in memory and this address may be assigned to a pointer. When a function is called it essentially causes an execution jump in the program to the location in memory where the instructions contained in the function are stored so it is possible to call a function using a pointer to a function. The address of a function is obtained by just using the function name without any parentheses, parameters or return type in much the same way as the name of an array is the address of the array.
A pointer to a function is declared as follows

Syntax : ret_type ( * fptr ) ( parameter list ) ;

where fptr is declared to be a pointer to a function which takes parameters of the form indicated in the parameter list and returns a value of type ret_type.
The parentheses around * fptr are required because without them the declaration
ret_type * fptr( parameter list ) ;
just declares a function fptr which returns a pointer to type ret_type ! fptr = getchar ; /* standard library function */

To call the function using a pointer we can do either of the following
ch = (*fptr)( ) ;
ch = fptr( ) ;
Example :- Program to compare two strings using a comparison function passed as a parameter.
#include <stdio.h>
#include <string.h>
void check( char *a, char *b, int ( * cmp ) ( ) );
void main( )
{
char s1[80], s2[80] ;
int (*p)( ) ;
p = strcmp ;
gets(s1) ;
gets( s2 );
check( s1, s2, p ) ;
}
void check ( char *a, char *b, int (* cmp)( ) )
{
if ( ! cmp( a, b ) )
puts( "equal" ) ;
else
puts( "not equal") ;
}
Pointers to Functions Pointers to Functions Reviewed by Unknown on 04:39 Rating: 5

No comments:

Powered by Blogger.