Safe Callback Invocation

#include <iostream>
using namespace std;

// Callback function that prints sensor data
void sensorCallback(int v) {
    cout << "DATA " << v;
}

int main() {
    int flag, value;
    // Reading input: flag (0 or 1) and the sensor value
    if (!(cin >> flag >> value)) return 0;

    // Define a function pointer that takes an int and returns void
    void (*callback)(int) = nullptr;   

    if (flag == 1) {
        // Assign the address of sensorCallback to the pointer
        callback = sensorCallback;
    }

    // --- Safe Callback Invocation ---
    // Check if the pointer is registered (not null) before calling
    if (callback != nullptr) {
        callback(value); // Invoke the function via the pointer
    } else {
        cout << "NO CALLBACK";
    }

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

0 10

Expected Output

NO CALLBACK