Wednesday, August 19, 2015

C Unions and Struct - A recap

The main difference between unions and struct is that union members overlay the memory of each other so that the size of the union is one, while struct 
members are laid out one after each other (with optional padding in between). Also a union is large enough to contain all its members, and have an alignment 
that fits all members For e.g. if int can only be stored at 2 byte address and is 2 bytes wide, and long can only be stored at 2 bytes address and is 4 bytes 
long. 

With this above, the following union could have size of 4 

union test
{
int a, 
long b
};

Both union and struct can have padding at the end, but not at the beginning. 

Writing to a struct changes only the value of the member written to. Writing to a member of union will render the value of all other members invalid. 

Another explanation is that struct is a record structure. each element in the struct allocates new space. 

struct  foobar
{
int foo;
long bar;
double baz;
}

this allocates at least sizeof(int) + sizeof(long) + sizeof(double) 

while the below, 

union foobar 
{
int foo;
long bar;
double baz;
}

this union allocates one chunk of memory and gives it 3 aliases. so, sizeof (footer) >= max (sizeof(int), sizeof(long), sizeof(double)) with possibility of some additional alignments. 

The best usecase is below 

Imagine an imaginary protocol like below 

struct packetHeader
{
int sourceaddress;
int destaddress;
int messagetype;
union request{
char fourcc[4];
int requestnumber;
}
}

In this protocol, based on the messageType, it can be either a request number or a 4 character code, but not both. In short, unions allow same storage to be used for multiple data types. 


References:

No comments:

Post a Comment