Introduction to Union in C Language
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.
Syntax
union <uname>
{
<Data-type1> var1;
<Data-type2> var2;
:
};
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.
Union variable
We can declare variables of a union just like structure.
Syntax:
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. |
#include<stdio.h> union demo { int a; float b; }; int main() { union demo d1; printf(“%d”,sizeof(d1)); d1.a=13; d1.b=5.5; printf(“\nd.a=%d”,d.a); printf(“\nd.b=%f”,d.b); return(0); } |
Output |
Size of union variable d=4 d.a=13137 d.b=4.600000 |
Description |
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. |