Skip to main content

Command Palette

Search for a command to run...

🌡️ Understanding Union in C++ with a Sensor Example

Published
4 min readView as Markdown

🧠 1. What is a Union?

A Union in C++ is a user-defined data type that allows you to store different types of data in the same memory location.

The key point is:
👉 Only one member of a union can hold a value at a time.

When you assign a new value to another member,
the previous value is overwritten, because all members share the same memory space.


🧱 2. Why Do We Need a Union?

Let’s say you are designing an IoT sensor device.
This device can send different types of readings, such as:

  1. Temperature (integer)

  2. Pressure (float)

  3. Status (character — for example, ‘O’ for OK or ‘E’ for Error)

At any moment, the device sends only one of these readings.
So, keeping memory for all three at once is unnecessary.

If we used a structure, it would reserve memory for all members,
which would waste space.


⚙️ 3. Example Using a Structure (Memory Waste)

#include <iostream>
using namespace std;

struct SensorData {
    int temperature;   // 4 bytes
    float pressure;    // 4 bytes
    char status;       // 1 byte
};

int main() {
    SensorData s;
    s.temperature = 30;
    s.pressure = 101.5;
    s.status = 'O';

    cout << "Temperature: " << s.temperature << endl;
    cout << "Pressure: " << s.pressure << endl;
    cout << "Status: " << s.status << endl;

    return 0;
}

🧮 Total memory used:
4 + 4 + 1 = 9 bytes (or more due to alignment)

But the device only needs one reading at a time,
so most of this memory is wasted.


⚙️ 4. Example Using a Union (Memory Efficient)

#include <iostream>
using namespace std;

union SensorData {
    int temperature;   // 4 bytes
    float pressure;    // 4 bytes
    char status;       // 1 byte
};

int main() {
    SensorData s;

    // Reading temperature
    s.temperature = 30;
    cout << "Temperature: " << s.temperature << "°C" << endl;

    // Now reading pressure (previous value lost)
    s.pressure = 101.5;
    cout << "Pressure: " << s.pressure << " kPa" << endl;

    // Now reading status (previous values lost again)
    s.status = 'O';
    cout << "Status: " << s.status << endl;

    return 0;
}

🧩 5. Step-by-Step Explanation

  • Step 1: When we store temperature = 30,
    memory holds the integer value.

  • Step 2: When we assign pressure = 101.5,
    the same memory location is reused, so the previous integer value is lost.

  • Step 3: When we assign status = 'O',
    the memory is overwritten again, and previous data is lost.

🧮 Total memory used:
Only 4 bytes (size of the largest member).

So, the union stores different types of data but uses just one memory block,
making it highly memory-efficient.


🧠 6. A More Realistic Example

Let’s improve it by taking user input to select what type of data to store:

#include <iostream>
using namespace std;

union SensorData {
    int temperature;
    float pressure;
    char status;
};

int main() {
    SensorData s;
    int choice;

    cout << "Enter data type (1 = Temperature, 2 = Pressure, 3 = Status): ";
    cin >> choice;

    if (choice == 1) {
        cout << "Enter temperature: ";
        cin >> s.temperature;
        cout << "Temperature: " << s.temperature << "°C" << endl;
    }
    else if (choice == 2) {
        cout << "Enter pressure: ";
        cin >> s.pressure;
        cout << "Pressure: " << s.pressure << " kPa" << endl;
    }
    else if (choice == 3) {
        cout << "Enter status (O/E): ";
        cin >> s.status;
        cout << "Status: " << s.status << endl;
    }
    else {
        cout << "Invalid choice!" << endl;
    }

    return 0;
}

✅ Explanation:

  • The user selects what type of data they want to enter.

  • Only that member of the union is used, and memory is not wasted.

  • When a new type is entered, it overwrites the old data.

This is how real embedded systems handle data efficiently when memory is limited.


⚖️ 7. Difference Between Structure and Union

FeatureStructureUnion
MemoryEach member gets its own spaceAll members share the same space
Data storedAll members can hold values at onceOnly one member can hold a value at a time
SizeSum of all members’ sizesSize of the largest member
Use CaseWhen all data is needed togetherWhen only one data type is needed at a time
ExampleStudent info (roll, name, marks)Sensor data (temp / pressure / status)

🧾 8. Key Points to Remember

  • Union saves memory by sharing one memory block for all members.

  • When you store a new value, it overwrites the previous one.

  • Use unions in low-memory environments (like sensors or embedded devices).

  • Size of a union = size of its largest member.

More from this blog

Amit singh's blog

235 posts