What is a function pointer in C?
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int calc(int (*op)(int, int), int x, int y) {
return op(x, y);
}
int main(void) {
printf("%d\n", calc(add, 10, 4));
printf("%d\n", calc(sub, 10, 4));
return 0;
}
Output:
Output of the above program is
14
6
The function calc() does not know which operation it will run. This idea is used for callbacks, menus and the compare function of qsort(). See Pointers and Functions.
Learn more about the similar topics:
| Tutorials |
|---|
| C Pointers |
| C Pointer Arithmetic |
| C Pointer to Pointer |
| C Pointers and Arrays |
| C Pointers and Functions |
| C Dynamic Memory Allocation |
| Exercises & Assignments |
|---|
| No Content Found. |