Pointer to a function in C language

In C, a variable that records the address of a function is known as a pointer. You can return a function from a function, send a function as an argument to another function, and even invoke a function indirectly by using a function pointer.

Syntax of declaring a function pointer:

return_type (*pointer_name)(argument_list);

Example:

#include <stdio.h>

int add(int a, int b) {
   return a + b;
}

int subtract(int a, int b) {
   return a - b;
}

int main() {
   int (*func_ptr)(int, int) = NULL;
   int a = 10, b = 5;
   char op = '+';

   if (op == '+') {
      func_ptr = add;
   } else if (op == '-') {
      func_ptr = subtract;
   }

   int result = func_ptr(a, b);
   printf("Result: %d\n", result);

   return 0;
}

Output:

Result: 15

In this example, we declare two functions add and subtract that take two integers and return an integer. We then declare a function pointer func_ptr that points to a function that takes two integers and returns an integer. We then assign func_ptr to point to the add function or the subtract function based on the value of op. Finally, we call the function using the function pointer, passing in a and b as arguments, and print the result.