65. Mode Selection Enum

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

enum class Mode : uint8_t { Input, Output, PullUp, PullDown };

const char* toString(Mode m) {
    switch (m) {
        case Mode::Input:    return "INPUT";
        case Mode::Output:   return "OUTPUT";
        case Mode::PullUp:   return "PULLUP";
        case Mode::PullDown: return "PULLDOWN";
    }
    return "INPUT"; // fallback
}

int main() {
    int x;
    cin >> x;

    Mode m = Mode::Input;
    if (x == 0)      m = Mode::Input;
    else if (x == 1) m = Mode::Output;
    else if (x == 2) m = Mode::PullUp;
    else if (x == 3) m = Mode::PullDown;

    cout << toString(m);
    return 0;
}

Solution Details

  • The enum is scoped and typed, preventing accidental use with raw ints.
  • toString provides a single conversion point for display and logs.
  • Mapping 0..3 keeps the input trivial while emphasizing enum usage.

     

Significance for Embedded Developers

  • GPIO mode configuration is a daily task; enums make it self-documenting and safe.
  • Strong typing prevents passing an invalid integer where a mode is expected.
  • Using uint8_t aligns with peripheral register fields.

     
Loading...

Input

0

Expected Output

INPUT