C function pointers
Created By: chatGPT
Function pointers are a powerful feature in C that allow you to store the address of a function in a variable. This enables you to easily pass functions as arguments, return them from other functions, or create arrays of functions. To declare a function pointer, you follow the syntax:
return_type (*PointerName)(parameter_types);
. This means you can treat the pointer as if it were the function itself.int (*funcPtr)(int, int);
Here’s a simple example where we define a function that adds two integers and then use a function pointer to call it. First, we define the function:
int add(int a, int b) {
return a + b;
}
Next, we define a function pointer and assign the address of the
add
function to it. We then call the function using the pointer.int main() {
int (*funcPtr)(int, int) = add;
int result = funcPtr(5, 3);
printf("Result: %d\n", result);
return 0;
}
Output from this program will be
Result: 8
. You can also create an array of function pointers.int subtract(int a, int b) {
return a - b;
}
int main() {
int (*operations[2])(int, int);
operations[0] = add;
operations[1] = subtract;
int sum = operations[0](5, 3);
int diff = operations[1](5, 3);
printf("Sum: %d, Difference: %d\n", sum, diff);
return 0;
}
In this example,
operations
is an array of function pointers that point to both add
and subtract
. You can then call these functions via their corresponding index in the array.Output:
Sum: 8, Difference: 2