73. LED RAII Controller

#include <iostream>
using namespace std;

class LEDController {
private:
    static int state;   // shared LED state

public:
    LEDController() {
        state = 1;      // LED ON when object is created
    }

    ~LEDController() {
        state = 0;      // LED OFF when object is destroyed
    }

    static void print() {
        cout << "LED=" << state << endl;
    }
};

int LEDController::state = 0;  // LED initially OFF

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

    {
        LEDController led;

        if (x == 1)
            LEDController::print();
    }

    LEDController::print();
    return 0;
}

Explanation & Logic Summary:

  • The LED state is stored in a static member, allowing access even after object destruction.
  • The constructor simulates enabling hardware (LED ON).
  • The destructor guarantees cleanup (LED OFF).
  • Scope boundaries demonstrate deterministic resource management.

Firmware Relevance & Real-World Context:

In embedded and firmware systems, RAII-style objects are commonly used to manage:

  • GPIO pins
  • Peripherals
  • Power domains

Destructors ensure predictable cleanup:

  • Turn off actuators
  • Disable peripherals
  • Release shared resources

This pattern reduces bugs caused by forgotten shutdown logic and improves system reliability.

 

 

 

 

 

Loading...

Input

1

Expected Output

LED=1 LED=0