C - Pointer to Function

In C, a pointer to a function is a variable that can store the address of a function. This allows you to call functions indirectly through the pointer, which can be useful for dynamic function dispatch or implementing callback mechanisms. Here's an example of how to declare, assign, and use a pointer to a function:

Example:


#include <stdio.h>

// Function to add two integers
int add(int a, int b) {
    return a + b;
}

// Function to subtract two integers
int subtract(int a, int b) {
    return a - b;
}

int main() {
    // Declare a pointer to a function that takes two integers and returns an integer
    int (*operation)(int, int);

    // Assign the address of the 'add' function to the pointer
    operation = add;

    // Use the pointer to call the 'add' function
    int result = operation(10, 5);
    printf("Addition result: %d\n", result);

    // Assign the address of the 'subtract' function to the pointer
    operation = subtract;

    // Use the pointer to call the 'subtract' function
    result = operation(10, 5);
    printf("Subtraction result: %d\n", result);

    return 0;
}
    

In this example:

  • We declare a pointer to a function named operation using the syntax int (*operation)(int, int);. This pointer can store the address of a function that takes two integers and returns an integer.
  • We assign the address of the add function to the operation pointer using operation = add;. Now, operation points to the add function.
  • We use the pointer to call the function indirectly by writing int result = operation(10, 5);. This invokes the add function through the pointer and stores the result in the result variable.
  • Later, we assign the address of the subtract function to the same operation pointer and use it to call the subtract function.

Output:


Addition result: 15
Subtraction result: 5
    

Pointer to function allows for dynamic selection of functions at runtime, making it useful in various scenarios like implementing callback mechanisms or creating extensible software where you can switch between different functions based on user input or other conditions.