Pointer to Function

Function Pointer Program in C++

IntermediateTopic: Memory Management Programs
Back

C++ Pointer to Function Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

// Function declarations
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 divide(int a, int b) {
    if (b != 0) {
        return a / b;
    }
    return 0;
}

int main() {
    // Declare function pointer
    int (*operation)(int, int);
    
    int num1 = 20, num2 = 5;
    
    // Point to add function
    operation = add;
    cout << num1 << " + " << num2 << " = " << operation(num1, num2) << endl;
    
    // Point to subtract function
    operation = subtract;
    cout << num1 << " - " << num2 << " = " << operation(num1, num2) << endl;
    
    // Point to multiply function
    operation = multiply;
    cout << num1 << " * " << num2 << " = " << operation(num1, num2) << endl;
    
    // Point to divide function
    operation = divide;
    cout << num1 << " / " << num2 << " = " << operation(num1, num2) << endl;
    
    // Array of function pointers
    int (*operations[])(int, int) = {add, subtract, multiply, divide};
    char opSymbols[] = {'+', '-', '*', '/'};
    
    cout << "\nUsing array of function pointers:" << endl;
    for (int i = 0; i < 4; i++) {
        cout << num1 << " " << opSymbols[i] << " " << num2 
             << " = " << operations[i](num1, num2) << endl;
    }
    
    return 0;
}
Output
20 + 5 = 25
20 - 5 = 15
20 * 5 = 100
20 / 5 = 4

Using array of function pointers:
20 + 5 = 25
20 - 5 = 15
20 * 5 = 100
20 / 5 = 4

Understanding Pointer to Function

A function pointer stores the address of a function. It allows you to call different functions dynamically. Function pointers are useful for: 1) Callback functions, 2) Implementing function tables, 3) Event handling, 4) Strategy pattern. The syntax is: returnType (*pointerName)(parameters). Arrays of function pointers enable switching between functions efficiently.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents