194. Command Dispatch Table

Back To All Submissions
Previous Submission
Next Submission
#include <iostream>

// Global command functions
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() {
    // TODO: Define an array of function pointers named 'dispatchTable'
    void  (*dispatchTable[])() = {cmdReset , cmdStart, cmdStop};
    // It should hold 3 pointers to functions returning void with no args.

    // Initialize it with {cmdReset, cmdStart, cmdStop}.
    // Syntax hint: void (*name[])() = { ... };
    
    int N;
    if (!(std::cin >> N)) return 0;

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

        // TODO: Check bounds (0 <= cmdID < 3)

        // If valid, call the function from the array: dispatchTable[cmdID]();
        if(cmdID >=0  && cmdID <3)
        {
            dispatchTable[cmdID]();
        }
        else
        {
         std::cout<<"Invalid Command\n";
         

        }
        // Else, print "Invalid Command"
    }
    return 0;
}

Solving Approach

 

 

 

 

 

 

Was this helpful?
Upvote
Downvote