43. ISR Callback Alias

#include <iostream>
#include <cstdint>

using namespace std;

// Alias for a function pointer that returns void and takes an int32_t
using ISRCallback = void (*)(int32_t);

void onError(int32_t code) {
    cout << "ERROR " << code;
}

void onComplete(int32_t code) {
    cout << "COMPLETE " << code;
}

int main() {
    int32_t mode, eventCode;
    if (!(cin >> mode >> eventCode)) return 0;

    // Declare the callback variable using the alias
    ISRCallback cb = nullptr;

    // Select callback based on mode
    if (mode == 1) {
        cb = onError;
    } else if (mode == 2) {
        cb = onComplete;
    }

    // Invoke through the function pointer
    if (cb) {
        cb(eventCode);
    }

    return 0;
}

Explanation & Logic Summary:

  • Type Aliasing
    using ISRCallback = void (*)(int32_t); creates a readable and reusable alias for a function pointer type, preferred over typedef in modern C++.
  • Decoupling
    The main logic does not depend on the implementation details of the callbacks, only on their interface.
  • Safety
    Initializing the function pointer to nullptr and checking before invocation prevents undefined behavior, which is critical in firmware systems.

Firmware Relevance & Real Embedded Meaning:

  • ISR-to-Application Communication
    This pattern is widely used in HALs and drivers to notify application code of hardware events without tight coupling.
  • Efficiency
    Function pointers provide deterministic and low-overhead dispatch compared to virtual functions, making them suitable for ISR-related paths.
  • Practical Skill
    Understanding and safely using function pointers is a foundational Embedded C++ skill for real-world firmware development.

 

 

 

 

 

Loading...

Input

1 42

Expected Output

ERROR 42