Function pointers in C are a powerful feature that allows you to store the address of a function in a variable and then call that function through the pointer. Function pointers are useful in scenarios where you need to select and call functions at runtime, making your code more flexible and extensible.
Here's how function pointers work in C:
Declaration of a Function Pointer: You declare a function pointer by specifying the return type and the parameter types that match the function you want to point to. The syntax is as follows:
c
return_type (*pointer_name)(parameter_type1, parameter_type2, ...);
For example, if you want to declare a function pointer that points to a function taking two integers as parameters and returning an integer, you would do it like this:
c
int (*addPtr)(int, int);
Assigning a Function to a Function Pointer: You can assign a function to a function pointer by using the function's name without parentheses. Here's how you do it:
c
int add(int a, int b) {
return a + b;
}
// Assign the add function to the addPtr pointer
addPtr = add;
Calling a Function Through a Function Pointer: To call the function through the function pointer, you use the pointer's name with parentheses, just like you would with a regular function call:
c
int result = (*addPtr)(5, 3); // This is equivalent to calling add(5, 3)
You can also omit the (* ... )
part, and C will still treat it as a function call:
c
int result = addPtr(5, 3); // Equivalent to (*addPtr)(5, 3)
Example: Here's a complete example that demonstrates function pointers in C:
c
#include <stdio.h> // Function to add two numbers int add(int a, int b) { return a + b; } // Function to subtract two numbers int subtract(int a, int b) { return a - b; } int main() { // Declare function pointers int (*operationPtr)(int, int); // Assign the add function to the pointer operationPtr = add; printf("Addition result: %d\n", operationPtr(5, 3)); // Assign the subtract function to the pointer operationPtr = subtract; printf("Subtraction result: %d\n", operationPtr(5, 3)); return 0; }
In this example, we declare a function pointer
operationPtr
, assign different functions to it, and call those functions through the pointer.
Function pointers are particularly useful in scenarios where you want to implement callbacks, function tables, or switch between different functions dynamically based on program conditions.
Comments
Post a Comment