We have seen examples of a pointer pointing to an integer but we can also have a pointer pointing to a function.
Ex:
#include<stdio.h>
void function1( int param1 )
{
printf( "Am inside function1: %d \n" , param1) ;
}
void function2( int param1 )
{
printf( "Am inside function2: %d \n" , param1) ;
}
main()
{
void (*POINTER_FUNCTION)(int a) ;
POINTER_FUNCTION = function1 ;
POINTER_FUNCTION(100) ;
POINTER_FUNCTION = function2 ;
POINTER_FUNCTION(200) ;
}
Output:
Am inside function1: 100
Am inside function2: 200
The declaration:
void (*POINTER_FUNCTION)(int a) ;
states that the "POINTER_FUNCTION" is a pointer to a function. However it is not just any function but a function with a particular signature. The function must take an int as an argument and return void.
The "POINTER_FUNCTION" is actually a variable and we can assign the address using the form:
POINTER_FUNCTION = function1 ;
and then invoke the pointer using :
POINTER_FUNCTION(100) ;
This ends up calling the function with an argument value of 100 . We can change the value that the pointer holds and assign the value of function 2 to it .
Ex:
#include<stdio.h>
void function1( int param1 )
{
printf( "Am inside function1: %d \n" , param1) ;
}
void function2( int param1 )
{
printf( "Am inside function2: %d \n" , param1) ;
}
main()
{
void (*POINTER_FUNCTION)(int a) ;
POINTER_FUNCTION = function1 ;
(*POINTER_FUNCTION)(100) ;
POINTER_FUNCTION = function2 ;
(*POINTER_FUNCTION)(200) ;
}
The above shows the syntax "(*POINTER_FUNCTION)(100)" that can be used to call the function also .
Ex:
#include<stdio.h>
void function1( int param1 )
{
printf( "Am inside function1: %d \n" , param1) ;
}
void function2( int param1 )
{
printf( "Am inside function2: %d \n" , param1) ;
}
main()
{
typedef void (*POINTER_FUNCTION_TYPE)(int a) ;
POINTER_FUNCTION_TYPE ptr = function1 ;
ptr(100) ;
ptr = function2 ;
ptr(200) ;
}
The notation
void (*POINTER_FUNCTION)(int a) ;
is kind of confusing . We are used to saying "int x1" where we have a type and then a variable of that type. We can use "typedef" to rewrite our program.
Using "typedef" above we define a type "POINTER_FUNCTION_TYPE" and then we can use this type to create a variable "ptr". This variable can hold the address of a function and is a function pointer.