Introduction to Union
It looks same as structure but implementation is different. Difference between structure and union is that the members of structure get different memory locations but members of a union share common memory location.
C Language Compiler allocates memory to hold that element of union which has the largest size.
uname is the name of union specified by programmer.
Data-type1, Data-type2,… are data types of elements of union.
var1, var2,… are members of union.
We can declare variables of a union just like structure.
union <tag_name> var1,var2,…..varN;
Here, tag_name is the name of union of which we want to declare variables.
var1,var2,……..varN are names of union variables.
|Program to demonstrate union.|
union demo d1;
|Size of union variable d=4|
|Size of d1 is displayed 4 because the size of largest element of union i.e. b(float type) is 4 bytes. The value of 1d.b is displayed correctly because union variable can hold value of only one of its elements at a time. The latest value stored is of d.b.|
Best Books of C