38. Function Pointer apply

#include <iostream>
#include <string>
using namespace std;

int square(int x) { return x * x; }
int cube(int x) { return x * x * x; }

void apply(int x, int (*op)(int)) {
    cout << op(x);
}

int main() {
    int n;
    string opName;
    cin >> n >> opName;

    if (opName == "square") {
        apply(n, square);
    } else if (opName == "cube") {
        apply(n, cube);
    }

    return 0;
}

 

Solution Details

  • apply doesn’t care which function it gets — it just calls the pointer.
  • Passing square or cube to apply lets you reuse the same logic.

👉 In simple words:
 Think of apply as a box where you put both a number and an instruction (square or cube). The box then gives you the result.

 

Significance for Embedded Developers

  • Function pointers are often used for callbacks in firmware (e.g., register a function that runs when a button is pressed, or when UART data arrives).
     
  • This pattern keeps code flexible — the function to execute can change at runtime.
     
Loading...

Input

5 square

Expected Output

25