Cover Image for C Function Pointer
113 views

C Function Pointer

The function pointer is a pointer that points to a function instead of pointing to a data value. Function pointers are a powerful feature of the C language and are used for various purposes, including callbacks, dynamic function selection, and implementing data structures like function tables. Here’s how you can declare, assign, and use function pointers in C:

C
#include <stdio.h>

// Declare a function pointer type for functions taking two integers and returning an integer.
typedef int (*BinaryFunction)(int, int);

// Example functions that match the function pointer type.
int add(int a, int b) {
    return a + b;
}

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

int multiply(int a, int b) {
    return a * b;
}

int main() {
    // Declare function pointers and initialize them with functions.
    BinaryFunction operation1 = add;
    BinaryFunction operation2 = subtract;
    BinaryFunction operation3 = multiply;

    // Use the function pointers to call the corresponding functions.
    int result1 = operation1(10, 5);  // Calls add(10, 5)
    int result2 = operation2(10, 5);  // Calls subtract(10, 5)
    int result3 = operation3(10, 5);  // Calls multiply(10, 5)

    printf("Result 1: %d\n", result1);
    printf("Result 2: %d\n", result2);
    printf("Result 3: %d\n", result3);

    return 0;
}

In this example:

  1. We define a function pointer type named BinaryFunction that represents functions taking two integers and returning an integer. This type is used to declare function pointers that can point to functions matching this signature.
  2. We define three functions (add, subtract, and multiply) that match the BinaryFunction signature.
  3. We declare function pointers (operation1, operation2, and operation3) and initialize them with the corresponding functions.
  4. We use these function pointers to call the functions they point to, which dynamically selects the operation to be performed.

Function pointers are powerful and flexible, allowing you to write more generic and extensible code. They are commonly used in situations like implementing callback mechanisms, creating function tables, and implementing plug-in systems.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS