example4_with_function_pointers.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

// Define a typedef for a function pointer
typedef int (*OperationFunc)(int, int);

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

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

void performOperation(int x, int y, OperationFunc op) {
    std::cout << "Result: " << op(x, y) << std::endl;
}

int main() {
    performOperation(5, 10, add);      // Calls add(5, 10)
    performOperation(5, 10, multiply); // Calls multiply(5, 10)
    return 0;
}
Back to typedef