A union is a memory location that is shared by two or more different types of variables. A union
provides a way of interpreting the same bit pattern in two or more different ways. Declaring a union
is similar to declaring a structure.
* Union and structure in C are same in concepts, except allocating memory for their members.
* Structure allocates storage space for all its members separately.
* Whereas, Union allocates one common storage space for all its members
* We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Where as Structure allocates storage space for all its members separately.
* Many union variables can be created in a program and memory will be allocated for each union variable separately.
* Below table will help you how to form a C union, declare a union, initializing and accessing the members of the union.
Type | Using normal variable | Using pointer variable |
Syntax | union tag_name { data type var_name1; data type var_name2; data type var_name3; }; |
union tag_name { data type var_name1; data type var_name2; data type var_name3; }; |
Example | union student { int mark; char name[10]; float average; }; |
union student { int mark; char name[10]; float average; }; |
Declaring union variable | union student report; | union student *report, rep; |
Initializing union variable | union student report = {100, “Mani”, 99.5}; | union student rep = {100, “Mani”, 99.5};report = &rep; |
Accessing union members | report.mark report.name report.average |
report -> mark report -> name report -> average |
Note:We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Where as Structure allocates storage space for all its members separately. |