Function Pointer in C
A function pointer in C is a pointer that points to a function instead of a variable. It can be used to call a function indirectly, which allows for more flexible and dynamic code, such as passing functions as arguments to other functions or implementing callback mechanisms.
Definition
A function pointer holds the memory address of a function, and can be used to call that function. Instead of calling a function by its name, you can use a function pointer to call it. This can be useful for callback functions, dynamic function calling, or implementing polymorphism in C.
The syntax for declaring a function pointer is:
Syntax:
return_type (*pointer_name)(parameter_types);
Example: Function Pointer
This example demonstrates how to declare and use a function pointer to call a function.
Example Code:
#include <stdio.h>
// Function declaration
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int main()
{
// Declare a function pointer
int (*func_ptr)(int, int);
// Assign the function pointer to the add function
func_ptr = add;
printf("Addition: %d\n", func_ptr(5, 3));
// Assign the function pointer to the subtract function
func_ptr = subtract;
printf("Subtraction: %d\n", func_ptr(5, 3));
return 0;
}
Output
Addition: 8
Subtraction: 2
Subtraction: 2
Key Points
- A function pointer stores the address of a function and can be used to call that function.
- Function pointers are useful for implementing callback functions, dynamic function calling, and other advanced techniques in C.
- Function pointers must be declared with the correct return type and parameter types to match the function they point to.
- By changing the function pointer to point to different functions, you can call different functions dynamically during runtime.
- Function pointers are commonly used in libraries and APIs to implement callbacks or event-driven programming.