31. Safe Callback Invocation

#include <iostream>
using namespace std;

// Callback function implementation
void sensorCallback(int v) {
    cout << "DATA " << v;
}

int main() {
    int flag, value;
    cin >> flag >> value;

    void (*callback)(int) = nullptr;  // optional callback pointer

    if (flag == 1) {
        callback = sensorCallback;    // register callback
    }

    if (callback == nullptr) {
        cout << "NO CALLBACK";
    } else {
        callback(value);              // safe callback invocation
    }

    return 0;
}

Explanation & Logic Summary:

  • The callback pointer is initialized to nullptr to represent “no callback registered”
  • When flag is 1, the callback function address is assigned
  • Before calling the function pointer, the program checks for nullptr
  • This prevents undefined behavior caused by invalid function-pointer calls

Firmware Relevance & Real-World Context:

  • Optional callbacks are common in embedded systems for:
    • UART receive handlers
    • DMA completion notifications
    • Timer expiration callbacks
    • ADC conversion completion
  • Calling a null function pointer can cause hard faults on microcontrollers
  • Using nullptr checks is a fundamental firmware safety pattern

 

 

 

Loading...

Input

0 10

Expected Output

NO CALLBACK