What is the usage of function pointers in the C language?
– Function pointers in C are variables that point to functions, allowing them to point to the starting address of a function. There are two main uses for function pointers.
- Function pointers as parameters: Function pointers can be used as parameters in a function, to pass the address of a function during a function call, allowing for calling other functions within the function. This can enable advanced function capabilities, such as callback functions. For example:
#include <stdio.h>
void print(int num) {
printf("%d\n", num);
}
void iterate(int start, int end, void(*func)(int)) {
for(int i = start; i <= end; i++) {
func(i);
}
}
int main() {
iterate(1, 5, print);
return 0;
}
- Function pointers as return values: Function pointers can also be used as return values, to return a pointer to a function. This allows for the ability to return different function addresses based on different conditions. For example:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int divide(int a, int b) {
return a / b;
}
int (*getOperation(char op))(int, int) {
switch(op) {
case '+':
return add;
case '-':
return subtract;
case '*':
return multiply;
case '/':
return divide;
default:
return NULL;
}
}
int main() {
int a = 10, b = 5;
char op = '+';
int (*operation)(int, int) = getOperation(op);
if(operation != NULL) {
int result = operation(a, b);
printf("%d\n", result);
} else {
printf("Invalid operator\n");
}
return 0;
}
Therefore, depending on the different operators, the corresponding function address can be returned, enabling different operations to be carried out.