12. Process Sensor Reading

#include <iostream>

// Overload for modification
void process(int& x) {
    x = x * 2;
}

// Overload for read-only use
void process(const int& x) {
    std::cout << "readonly";
}

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

    if (x < 0) {
        process(static_cast<const int&>(x));   // read-only
    } else {
        process(x);                            // modification
        std::cout << x;
    }

    return 0;
}

Explanation & Logic Summary:

  • Two overloaded versions of the process are defined.
  • The non-const reference overload allows modification of the input.
  • The const-reference overload enforces read-only access.
  • Overload resolution is performed by the compiler based on constness.
  • This pattern prevents accidental modification of protected data.

Firmware Relevance & Real-World Context:

  • Embedded firmware frequently distinguishes between read-only and writable access to data.
  • Const-correct APIs prevent unintended side effects in drivers and HAL layers.
  • This pattern is commonly used for sensor data, calibration values, and system state access.
  • Understanding const-based overloading is essential for safe firmware design.

     

 

 

 

Loading...

Input

5

Expected Output

10