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>
typedefunionPacket{intiData;doubledData;charcData;}Packet;externPacketread_next_packet();intmain(){Packetreceived=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?
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
This snippet isn't complete on its own --- you need some way to tell whether a
Packet
is going to be anint
,double
, orchar
. Consider:All three
printf
statements will run, and two of the three will produce undefined behavior. What happens ifreceived
is achar
and I try to accessreceived.dData
? What value do the other 7 bytes of the 8-bytedouble
take?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.