Safe Sensor nullptr Check

#include <iostream>
using namespace std;

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

    int* sensorPtr = nullptr;   // optional sensor pointer

    if (flag == 1) {
        sensorPtr = new int;    // allocate memory
        cin >> *sensorPtr;      // read sensor value
    }

    // nullptr check and output logic
    if (sensorPtr == nullptr) {
        cout << "NO SENSOR";
    } else {
        cout << *sensorPtr;
    }

    // Free allocated memory (safe even if sensorPtr == nullptr)
    delete sensorPtr;
    sensorPtr = nullptr;

    return 0;
}

Solving Approach

 

 

 

 

 

 

Upvote
Downvote
Loading...

Input

0

Expected Output

NO SENSOR