wat is d real time application of union....
wat is d real time application of union....
hi friend
A "union declaration" specifies a set of variable values and, optionally, a tag naming the union. The variable values are called "members" of the union and can have different types. Unions are similar to "variant records" in other languages
Thanks
Deepasree
A union is a variable typed by the keyword union, which may hold at different types and sizes. Union provides a way to manipulate different kinds of data ina single storage, ie. the purpose of union is to provide a single variable, which can hold any 1 of the several types, defined.
Unions are useful for applications involving, multiple members, where values need not b assigned to all the members at any instant.
You are right.
A practical example is listed below.
Let us say that there are two types of blocks.
blk_type == A; dependent data is an integer
blk_type == B; dependent data is a char array of 4 bytes.
We can define the structures:
struct blkA {
int a;
}
struct blkB {
char b[4];
}
But, this would mean that all functions now have to deal with two different block types: different prototypes, etc. Leads to lot of code bloat.
We could do better like below:
struct block {
blk_type;
int a;
char b[4];
}
But, this would lead to wastage of space. How?? Total space allocated is 8 bytes, apart from block type. When block type is A, we will not use b[4], and when block type is B, we will not use int a. So, at any time, 4 bytes are wasted.
We can do even better by using unions.
struct block {
blk_type;
union {
int a;
char b[4];
};
};
The advantage of a union is that space is allocated only once for the highest sized member of the union. In our example above, we will allocate only 4 bytes (assuming int is 4 bytes). And the same 4 bytes is used whether it is block type A or B. And, apart from savings in space, we can have one routine dealing with both block types, depend on the block type field.
Hope that helps.