5. Read-Only SensorData Reference

#include <iostream>

const int* ptr = nullptr;

struct SensorData {
    int x;
    int y;
    int z;
};

// Pass by const reference:
// - avoids copying
// - enforces read-only access at compile time
void print_data(const SensorData& d) {

    // d.x = 99;  // compilation error if uncommented
    std::cout << d.x << " " << d.y << " " << d.z << '\n';

    // Safe: pointer to const int
    ptr = &d.x;
}

int main() {
    SensorData data;
    std::cin >> data.x >> data.y >> data.z;

    print_data(data);

    if (&data.x != ptr) {
        std::cout << "Failed\n";
    }

    return 0;
}

Explanation & Logic Summary:

  • const SensorData& ensures:

    • No copy of the struct is made
    • The compiler prevents modification of d

    ptr is declared as const int*, so storing &d.x is safe and legal.

  • The address comparison in main() verifies:
    • No copy occurred
    • The function accessed the original object

 

Firmware Relevance & Real-World Context:

Embedded systems frequently pass sensor data by reference to avoid stack usage and copying overhead.

  • Const-correctness:

    • Prevents accidental writes to hardware-backed data
    • Enables static analysis and MISRA compliance

    Pointer exposure is common in low-level firmware APIs.

  • This task tests three critical embedded skills:

    • Const-correct API design
    • Reference vs copy semantics

    Safe interaction between references and pointers

 

 

 

Loading...

Input

3 4 5

Expected Output

3 4 5