47. 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 "UNKNOWN"; // defensive 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;
}

Explanation & Logic Summary:

A scoped enum class is used to provide strong typing and prevent unintended implicit conversions between integers and enum values.
The toString() function converts enum values into human-readable string literals, a common requirement in firmware logging, debugging, and diagnostics.

The integer-to-enum mapping is explicitly defined and constrained to valid values, ensuring deterministic behavior suitable for embedded systems.

Firmware Relevance & Real Embedded Meaning:

GPIO configuration is a fundamental task in embedded firmware.
Using scoped enums with fixed underlying types (uint8_t) improves:

  • Type safety
  • Readability
  • Maintainability
  • Alignment with hardware register fields

This problem reinforces best practices for Embedded C++ enum usage commonly found in real-world firmware and HAL implementations.

 

 



 

Loading...

Input

0

Expected Output

INPUT