152. Command Dispatch Table

#include <iostream>

void cmdReset() { std::cout << "System Reset" << std::endl; }
void cmdStart() { std::cout << "System Start" << std::endl; }
void cmdStop()  { std::cout << "System Stop" << std::endl; }

int main() {
    // Defining the array of function pointers
    // The syntax is: return_type (*array_name[])(args)
    void (*dispatchTable[])() = { cmdReset, cmdStart, cmdStop };

    int N;
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        int cmdID;
        std::cin >> cmdID;

        if (cmdID >= 0 && cmdID < 3) {
            // Direct access via index - O(1) complexity
            dispatchTable[cmdID](); 
        } else {
            std::cout << "Invalid Command" << std::endl;
        }
    }
    return 0;
}

Explanation & Logic Summary:

  • The Array: void (*dispatchTable[])() creates an array where every element is a void (*)() (a pointer to a function).
  • The Dispatch: Instead of comparing cmdID against 0, then 1, then 2 (like in if-else), the CPU calculates the memory address base_address + (cmdID * pointer_size) and jumps there immediately.
  • Efficiency: As the number of commands grows to 100 or 1000, the speed of this solution stays exactly the same (O(1)), whereas a switch-case or if-else chain would get slower.

Firmware Relevance & Real-World Context:

  • USB Device Stack: When a USB "Setup Packet" arrives, byte 2 acts as the Request ID. Stacks use dispatch tables to route standard requests (GetDescriptor, SetAddress) instantly.
  • State Machines: In a Finite State Machine (FSM), the "Current State" is often just an index into an array of function pointers representing the logic for each state.

 

 

 

Loading...

Input

3 1 0 5

Expected Output

System Start System Reset Invalid Command