In C, pointers can not only point to data variables but also to functions. A pointer to a function allows you to call a function indirectly through the pointer, enabling dynamic function calls and the implementation of callback mechanisms. This concept is useful in scenarios like event handling and passing functions as arguments to other functions.
Program: Pointer to Function
Here's a simple C program that demonstrates the use of pointers to functions:
Explanation of the Program
Header Files:
#include <stdio.h>
: This header file is included for input/output functions likeprintf
andscanf
.
Function Prototypes:
- The function prototypes declare the functions
add
,subtract
,multiply
, anddivide
that will be defined later.
- The function prototypes declare the functions
Function Pointer Declaration:
void (*operation)(int, int);
: This line declares a pointer namedoperation
that can point to any function taking twoint
parameters and returningvoid
.
User Input:
- The program prompts the user to enter two numbers and an operation (
+
,-
,*
, or/
).
- The program prompts the user to enter two numbers and an operation (
Function Pointer Assignment:
- A
switch
statement checks the operator entered by the user and assigns the appropriate function to theoperation
pointer.
- A
Calling the Function:
- The function is called indirectly using the pointer:
operation(num1, num2);
. This line calls the function thatoperation
points to, passing the two numbers as arguments.
- The function is called indirectly using the pointer:
Function Implementations:
- Each function (
add
,subtract
,multiply
, anddivide
) performs the respective operation and prints the result. Thedivide
function also checks for division by zero to prevent runtime errors.
- Each function (
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code:Execute the Program:
Example Output
When you run the program, the output might look like this:
Or for another operation:
Conclusion
This program demonstrates how to use pointers to functions in C, enabling dynamic function calls based on user input. Understanding function pointers allows for more flexible and reusable code, as functions can be passed around like variables. This concept is particularly useful in implementing callback functions, handling events, and designing more modular code.