Table of contents
INTRODUCTION TO FUNCTION POINTERS
Function pointers in C are variables that can store the memory address of functions and can be used in a program to create a function call to functions pointed by them. It is a special pointer that points to a function. It points to a block of code of a function.
return type of function (* pointer_name) (datatype of arguments);
int (*ptr) (int, int) = &func;
where &func is the address of the function func().
ptr is the pointer.
(int, int) are the datatype of the argument passed in func().
#include <stdio.h>
int sum(int a, int b);
int main(void)
{
int calc = 0;
int (*ptr) (int, int) = ∑
calc = (*ptr) (2,3);
printf("%d\n", calc);
return (0);
}
int sum(int a, int b)
{
return (a + b)
}
Function pointers are also used as callback functions. Callback functions are functions passed to another function as an argument. Let's consider a simple calculator.
#include <stdio.h>
void sub(int a, int b);
void add(int a, int b);
void display(void (*fptr)(int, int));
int main(void)
{
display(&add);
display(sub); //it is optional to add the ampersand when calling a function
return (0);
}
void add (int a, int b)
{
printf("The sum of %d and %d is %d\n", a, b, a + b);
}
void sub(int a, int b)
{
printf("The difference of %d and %d is %d\n", a, b, a - b);
}
void display (void (*fptr)(int, int))
{
(*fptr) (5, 1);
}
In the example above, we passed the function pointer which points to a function as an argument to another function(display). We then call the functions in the main function.
APPLICATIONS OF FUNCTION POINTERS
Function pointers are used in many ways in C programming. Some of the applications of function pointers include:
Callbacks
Storing functions in an array
Resolving run-time binding: This refers to deciding the proper function during runtime instead of compile time. Function pointers can be used to achieve this.
In cases of using a switch statement, function pointers can be used.
Most common application will use them as callback handlers on events. The core module, calls the function pointers designated as event handlers when event hits.