63. Packet Field ID or Value

#include <iostream>
#include <string>
#include <cstdint>
using namespace std;

enum class Kind : uint8_t { Id, Value };

struct Packet {
    Kind kind;
    union {
        uint16_t id;
        int32_t value;
    };
};

int main() {
    string type;
    int num;
    cin >> type >> num;

    Packet p;
    if (type == "Id") {
        p.kind = Kind::Id;
        p.id = (uint16_t)num;
    } else if (type == "Value") {
        p.kind = Kind::Value;
        p.value = num;
    }

    if (p.kind == Kind::Id) {
        cout << "ID=" << p.id;
    } else if (p.kind == Kind::Value) {
        cout << "VALUE=" << p.value;
    }

    return 0;
}

 

Solution Details

  • tagged union combines a union (for compact storage) with a tag (Kind) that tells us which member is valid.
  • If kind == Kind::Id, we read/write id.
  • If kind == Kind::Value, we read/write value.
  • This prevents confusion and ensures safe access to the correct union field.
     

👉 In simple words: The tag (Kind) acts like a label saying “right now this union holds an ID” or “right now it holds a Value.”

 

Significance for Embedded Developers

  • Common in protocol messages where a field can mean different things depending on a tag.
     
  • Example: A packet may contain either a device ID or a data value, but not both at the same time.
     
  • Saves memory and keeps data layout compact — critical in low-memory systems.
     
Loading...

Input

Id 42

Expected Output

ID=42