39. Button Press Callback

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

void onPressA() { cout << "Button A pressed\n"; }
void onPressB() { cout << "Button B pressed\n"; }

void simulatePress(void (*callback)()) {
    callback(); // call the function passed in
}

int main() {
    string input;
    cin >> input;

    if (input == "A") {
        simulatePress(onPressA);
    } else if (input == "B") {
        simulatePress(onPressB);
    }

    return 0; }

 

Solution Details

  • simulatePress takes a function pointer callback.
  • When called, it runs whichever function is passed (onPressA or onPressB).
  • This shows how the program can register different behaviors dynamically.

     

👉 In simple words:
 Think of the button as a doorbell. The callback is who answers the door. You can change who answers without changing the doorbell itself.

 

Significance for Embedded Developers

  • This is exactly how interrupts and callbacks work in firmware.
     
  • Example:
    • A GPIO button press triggers an interrupt.
    • The programmer sets a callback that runs when the interrupt fires.
       
  • This makes code modular — you can reuse the same button code but change the action as needed.

     
Loading...

Input

A

Expected Output

Button A pressed