Introduction
Pointer to a function is a way to store the memory address of a function just like a variable stores the memory address of a value. When a function is called through a pointer, it is called pointer to a function.
In this lab, we will write a C program to demonstrate how to use a pointer to a function.
Declare and define the function to be pointed to
In this step, we will declare and define a function which takes two integer arguments and does not return anything.
#include<stdio.h>
void func(int a, int b)
{
printf("\n\n a = %d \n", a);
printf("\n\n b = %d \n", b);
}
Declare a pointer to a function
In this step, we will declare a pointer to the function created in step 1. The syntax for declaring a pointer to a function is similar to that for declaring a pointer to a variable, but it specifies the parameter types and return type of the function being pointed to.
// function pointer
void (*fptr)(int , int);
Store the address of the function in the pointer
In this step, we will store the address of the function created in step 1 in the pointer created in step 2.
// assign address to function pointer
fptr = func;
Call the function using the pointer
In this step, we will call the function that we created in step 1 using the pointer to the function created in step 2.
// function calling
func(2,3);
fptr(2,3); // calling a function referring to pointer to a function
Write the full code
Open the main.c file in the ~/project/ directory.
#include<stdio.h>
void func(int a, int b)
{
printf("\n\n a = %d \n", a);
printf("\n\n b = %d \n", b);
}
int main()
{
printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
// function pointer
void (*fptr)(int , int);
// assign address to function pointer
fptr = func;
// function calling
func(2,3);
fptr(2,3); // calling a function referring to pointer to a function
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}
Compile and run the code
To compile the code, open the terminal and type the following command:
gcc main.c -o main
To run the program, type the following command:
./main
Summary
In this lab, we learned how to use a pointer to a function in a C program. We saw how to declare and define the function to be pointed to, how to declare a pointer to a function, how to store the address of the function in the pointer, and how to call the function using the pointer. The use of pointers to a function can make complex programs easier to write and understand.



