DEV Community

Discussion on: On `union` in C

Collapse
 
gefjon profile image
Phoebe Goldman

This snippet isn't complete on its own --- you need some way to tell whether a Packet is going to be an int, double, or char. Consider:

#include <stdio.h>

typedef union Packet {
    int iData;
    double dData;
    char cData;
} Packet;

extern Packet read_next_packet();

int main() {
    Packet received = read_next_packet();
    printf("`received.iData` is %d\n", received.iData);
    printf("`received.dData` is %f\n", received.dData);
    printf("`received.cData` is %c\n", received.cData);
}

All three printf statements will run, and two of the three will produce undefined behavior. What happens if received is a char and I try to access received.dData? What value do the other 7 bytes of the 8-byte double take?

Collapse
 
wiz profile image
wiz

Yeah, you are absolutely right.The snippet is not complete and also buggy if implemented but there must be some support code to handle such issues. I don't know that now. What I wanted to tell is just the use of the union.
When you have, say 10 different types of data coming and you know very well that at a time only one type of data will be stored. So there is no point in using struct since it will consume a lot of memory. Considering cases like such the notion of the union was introduced in C because we also not had much memory that time.