Function Pointer in C

1. Function Pointers in C

A function pointer in C is a pointer that stores the address of a function. This allows functions to be called indirectly, making them useful for callbacks, dynamic function calls, and implementing polymorphism in C.

2. Declaring and Using Function Pointers

return_type (*pointer_name)(parameter_list);

  • return_type → The return type of the function.
  • pointer_name → Name of the function pointer.
  • parameter_list → The function's parameter types.

3. Basic Example of Function Pointer

#include "stdio.h"

// A normal function that takes two integers and returns an integer
int add(int a, int b) {
    return a + b;
}

int main() {
    // Declare a function pointer
    int (*funcPtr)(int, int);

    // Assign function address to pointer
    funcPtr = add;

    // Call function using pointer
    int result = funcPtr(10, 20);

    printf("Sum: %d\n", result); // Output: Sum: 30

    return 0;
}

Explanation:

  • We declare a function add().
  • We define a function pointer funcPtr that can point to a function taking two int parameters and returning an int.
  • We assign the address of add to funcPtr.
  • We call add using funcPtr(10, 20), and it works just like a normal function call.