Function Pointer in C
In this program, you will learn about the function pointer and get the example code of function pointer in c programming.
What is Function Pointer in C
A function pointer is a pointer which stores the address of a function. It is used to call a function indirectly in C programming. Function pointers are mainly used for callback functions in C programming. A callback function is a function which is called by another function.
Syntax
<return_type> (*function_pointer_name)(parameter_list);
For ex. – You have a function like numberSum that takes two int as parameters and returns an int, you can make a pointer to it like this:
int (*sumPointer)(int, int) = &numberSum;
Function Pointer in C example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <stdio.h> // Functon pointer int (*f_ptr)(int, int); // Function declaration int addNum(int, int); int subNum(int, int); // function of add number int addNum(int x, int y) { return (x + y); } // function of sub number int subNum(int x, int y) { return (x - y); } int main() { int x = 20, y = 40; // Function pointer initialization f_ptr = &addNum; // result print printf("\nSum = %d\n", f_ptr(x, y)); // function Change f_ptr = &subNum; // result print printf("\nDifference = %d\n", f_ptr(x, y)); return 0; } |
Output
Addition = 60
Substraction = -20
Check out our other C programming Examples