C Function Pointer

A function pointer in C is a pointer that points to a function rather than a data value (like an integer or a character). This means the pointer holds the memory address of a function.

Function pointers are useful because they allow you to call a function indirectly, pass functions as arguments to other functions, or even return functions from other functions.

Syntax:


return_type (*pointer_name)(parameter_types);

Explanation:

  • return_type: The return type of the function the pointer will point to.
  • pointer_name: The name of the pointer.
  • parameter_types: The types of parameters the function accepts.

Example:


#include <stdio.h>

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

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

    // Assign the function pointer to the function
    fun_ptr = add;

    // Call the function using the pointer
    int result = fun_ptr(10, 20);  // Equivalent to add(10, 20)
    printf("Result: %d\n", result);  // Output: 30

    return 0;
}

Output:

30

Explanation:

  • int (*fun_ptr)(int, int); declares fun_ptr as a pointer to a function that takes two int arguments and returns an int.
  • fun_ptr = add; assigns the address of the add function to the function pointer fun_ptr.
  • fun_ptr(10, 20) calls the function add(10, 20) via the function pointer.