Union in C Programming : Introduction and Basic Notes
Union in C Programming :
In C Programming we have came across Structures. Unions are similar to structure syntactically.Syntax of both is almost similar. Let us discuss some important points one by one -
Note #1 : Union and Structure are Almost Similar
union stud { int roll; char name[4]; int marks; }s1; | struct stud { int roll; char name[4]; int marks; }s1; |
If we look at the two examples then we can say that both structure and union are same except Keyword.
Note #2 : Multiple Members are Collected Together Under Same Name
int roll; char name[4]; int marks;
We have collected three variables of different data type under same name together.
Note #3 : All Union Members Occupy Same Memory Area
For the union maximum memory allocated will be equal to the data member with maximum size. In the example character array ‘name’ have maximum size thus maximum memory of the union will be 4 Bytes.
Maximum Memory of Union = Maximum Memory of Union
Data Member
Note #4 : Only one Member will be active at a time.
Suppose we are accessing one of the data member of union then we cannot access other data member since we can access single data member of union because each data member shares same memory. By Using Union we can Save Lot of Valuable Space
Simple Example :
union u { char a; int b; }