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.
Interview Questions & Answers
What is a pointer in C?
What is a NULL pointer in C?
What is the difference between malloc() and calloc() in C?
What is a memory leak in C and how to avoid it?
What is a dangling pointer in C?
What is the difference between an array and a pointer in C?
What is a void pointer in C?