70. ADCChannel Constructor Validation

#include <iostream>
using namespace std;

class ADCChannel {
private:
    int channel;
    int resolution;

public:
    ADCChannel(int ch, int res) {
        // Validate channel
        if (ch < 0) channel = 0;
        else if (ch > 15) channel = 15;
        else channel = ch;

        // Validate resolution
        if (res == 8 || res == 10 || res == 12)
            resolution = res;
        else
            resolution = 12; // safe default
    }

    void print() {
        cout << "CH=" << channel << " RES=" << resolution;
    }
};

int main() {
    int ch, res;
    cin >> ch >> res;

    ADCChannel adc(ch, res);
    adc.print();

    return 0;
}

Explanation & Logic Summary:

  • The constructor guarantees the object always enters a valid state.
  • ADC channels are clamped to the hardware-supported range (0–15).
  • Unsupported ADC resolutions fall back to a safe default (12 bits).
  • This defensive initialization pattern prevents invalid peripheral configuration in firmware.

Firmware Relevance & Real-World Context:

  • ADC peripherals accept only limited channel indices and resolution settings.
  • Invalid configuration can stall peripherals or corrupt data.
  • Embedded drivers must validate parameters before writing to hardware registers.
  • This constructor models safe, real-world firmware initialization practices.

 

 

 

 

Loading...

Input

3 10

Expected Output

CH=3 RES=10