Function Pointer in C

What is Function Pointer in C ?

In C, a function pointer refers to a variable that stores the address of a function rather than the data value itself. This dynamic mechanism is akin to having a tool that can change its purpose based on what function it points to. Function pointers provide a way to implement complex and versatile behaviors, making your code more organized and efficient.

Declaring Function Pointers

To declare a function pointer, you need to specify the return type and parameter types of the function it will point to. For instance:

int (*funcPtr)(int, int);

Here, funcPtr is a pointer to a function that takes two integer arguments and returns an integer.

Assigning Functions to Pointers

After declaring a function pointer, you can assign a compatible function’s address to it:

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

int (*funcPtr)(int, int) = add;

Invoking Functions using Pointers

To call the function using a pointer, you can use the dereference operator:

int result = (*funcPtr)(5, 3);

Array of Function Pointers

Arrays of function pointers are immensely useful for tasks like event handling or managing a collection of related functions.

int (*mathOperations[3])(int, int) = {add, subtract, multiply};

Passing Function Pointers as Arguments

Function pointers can be passed as arguments to other functions, allowing you to create dynamic behaviors.

void execute(int (*function)(int, int), int a, int b) {
    int result = function(a, b);
    printf("Result: %d\n", result);
}

Returning Function Pointers

Yes, you can even return a function pointer from a function.

int (*getOperation())(int, int) {
    return add;
}

Callback Functions

Callback functions, a common use of function pointers, enable you to define a function that is later called when a specific event occurs.

void eventHandler(int (*function)(int, int)) {
    int result = function(10, 5);
    printf("Event Result: %d\n", result);
}

Function Pointers vs. Regular Pointers

Function pointers might seem similar to regular pointers, but they point to functions rather than data. They provide a unique level of abstraction and can be instrumental in creating dynamic and adaptable code.

Benefits of Using Function Pointers

  • Dynamic Behavior: Function pointers allow for runtime decision-making, enhancing the flexibility of your code.
  • Code Reusability: They enable the reuse of functions across different parts of your program.
  • Modularity: Function pointers promote modularity, making your code easier to manage and understand.
  • Polymorphism: Function pointers contribute to achieving polymorphic behavior in C.

Examples of Function Pointer:

Sorting an Array using Function Pointers

#include <stdio.h>

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

// Function to perform bubble sort using function pointers
void bubbleSort(int arr[], int size, int (*cmp)(int, int)) {
    int temp;
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if ((*cmp)(arr[j], arr[j + 1]) > 0) {
                // Swap arr[j] and arr[j+1]
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int numbers[] = {4, 1, 7, 3, 9};
    int size = 5;

    // Sort the array using bubbleSort and the compare function
    bubbleSort(numbers, size, compare);

    // Print the sorted array
    printf("Sorted Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

Output:

Sorted Array: 1 3 4 7 9

This example demonstrates sorting an array of integers using the bubble sort algorithm with a function pointer compare to determine the sorting order.

Event Handling with Function Pointers

#include <stdio.h>

// Define a function pointer type for event handlers
typedef void (*EventHandler)(int);

// Event handler function for a button click
void onClick(int button) {
    printf("Button clicked with code: %d\n", button);
}

// Event handler function for mouse hover
void onHover(int x, int y) {
    printf("Mouse hovered at (%d, %d)\n", x, y);
}

int main() {
    // Declare function pointer variables
    EventHandler clickHandler = onClick;
    EventHandler hoverHandler = onHover;

    // Simulate button click and mouse hover events
    clickHandler(1);        // Simulating a button click event
    hoverHandler(100, 50);  // Simulating a mouse hover event

    return 0;
}

Output:

Button clicked with code: 1
Mouse hovered at (100, 50)

This example demonstrates the use of function pointers for event handling, where different event handlers (onClick and onHover) are assigned to function pointer variables and called to simulate events.

Function Pointers in Data Structures

#include <stdio.h>

// Function to perform addition
int add(int a, int b) {
    return a + b;
}

// Function to perform subtraction
int subtract(int a, int b) {
    return a - b;
}

// Define a data structure to store a math operation and its name
typedef struct {
    char* name;
    int (*operation)(int, int);
} MathFunction;

int main() {
    // Create instances of MathFunction
    MathFunction addFunc = {"Addition", add};
    MathFunction subFunc = {"Subtraction", subtract};

    // Perform math operations using function pointers
    int result1 = addFunc.operation(5, 3);
    int result2 = subFunc.operation(5, 3);

    // Print the results
    printf("%s result: %d\n", addFunc.name, result1);
    printf("%s result: %d\n", subFunc.name, result2);

    return 0;
}

Output:

Addition result: 8
Subtraction result: 2

In this example, we define a data structure MathFunction to store a math operation along with its name. We use function pointers within the structure to perform mathematical operations (add and subtract), and then we print the results.