69. Enum with Switch Dispatch

 #include <iostream>
#include <string>
using namespace std;

enum class Command { Start, Stop, Reset };

void execute(Command c) {
    switch (c) {
        case Command::Start: cout << "STARTING...";  break;
        case Command::Stop:  cout << "STOPPING...";  break;
        case Command::Reset: cout << "RESETTING..."; break;
    }
}

int main() {
    string cmd;
    cin >> cmd;

    Command c = Command::Start; // default
    
    if (cmd == "Start")      c = Command::Start;
    else if (cmd == "Stop")  c = Command::Stop;
    else if (cmd == "Reset") c = Command::Reset;

    execute(c);
    return 0;
}

 

 Solution Details

  • The enum Command defines discrete commands: Start, Stop, Reset.
     
  • The program reads a string and assigns the correct enum value.
     
  • execute(Command) uses a switch to handle each case, printing the right action.
     
  • This avoids long chains of if-else and makes dispatch explicit and type-safe.

     

Significance for Embedded Developers

  • Command parsing is common in communication protocols and debug shells.
     
  • Using enums ensures only valid commands are represented, avoiding invalid string/integer errors.
     
  • A switch makes the dispatch logic clear and efficient.

     
Loading...

Input

Start

Expected Output

STARTING...