Union is the user-defined data type used to wrap up one or more variables that may be in different data types into a single variable at a single memory location. C unions are similar to the structure in concepts, except for allocating memory for its members.
Structure allocates storage space for all its members separately, whereas c unions allocate one common storage space for all its members.
Difference between structure and C unions
- Union allocates one common storage space for all its members
- In a union, if any of the data element’s values is changed then the other data element value even changes, i.e. the value of one data element of a union depends on all other data elements.
- The only major advantage that a union has over structure is to save memory space.
- Union holds value for one data type which requires larger storage among its members.
Syntax:
1 2 3 4 5 6 |
union union_tag { <data-type> element 1; <data-type> element 2; <data-type> element 3; }union_variable; |
Example:
1 2 3 4 5 6 |
union student { int id; char name[20]; float percentage; } student1; |
Accessing Union Members
Syntax:
1 |
union_var.member; |
To access members of a union you use the (.) operator, for instance: student1.name