<aside> <img src="/icons/home_green.svg" alt="/icons/home_green.svg" width="40px" />

Back to Home

</aside>

https://jennychen9827.github.io/CAD281/functionPointers.html

Why We Need Function Pointers in C

Function pointers provide additional flexibility and power:

Simple Code Example

#include <stdio.h>

// Function prototypes
int add(int a, int b);
int subtract(int a, int b);

// Function pointer type definition
typedef int (*Operation)(int, int);

// Function that uses a function pointer
void performOperation(int a, int b, Operation op) {
    printf("Result: %d\\n", op(a, b));
}

int main() {
    int x = 10, y = 5;

    // Using function pointers
    Operation add_ptr = add;
    Operation subtract_ptr = subtract;

    performOperation(x, y, add_ptr);      // Calls add function
    performOperation(x, y, subtract_ptr); // Calls subtract function

    return 0;
}

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

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

This example demonstrates the use of functions and function pointers. The performOperation function takes a function pointer as an argument, allowing it to flexibly perform different operations based on the function passed to it.